'Firestore: query where clause > nested field

I'm using Flutter and Firestore. Suppose my database looks like this:

[
  {
    Name: 'John',
    Address: {
      Street: "John doe street"
      Postal: "12047"
    }
  },
  {
    Name: 'Mary',
    Address: {
      Street: "Fleet street"
      Postal: "1242B"
    }
  }
]

I now would like to search for all persons whose postal code contains '12'. So that would mean both records in this dummy database.

But how can I filter on the nested field 'Address.Postal'?

var ref = FirebaseFirestore.instance;
var query = '12';
ref.collection('users')
        .where(
          'Address.Postal', // Won't work
          ... // There is no 'like' operator or something that looks alike
        );

FYI the project being in Flutter is irrelevant.



Solution 1:[1]

There is no way to check for a specific property in the array items. All you can do is check whether the entire item is present with array-contains. But for that you need to know the entire array item, so all name and address properties.

If you only have the name, there is no built-in operator to test whether any array item contains that name. Instead you'll want to extract just the names into their own array (say addressNames) and then use array-contains on that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen