How to query a firestore array with multiple key value pairs in Swift

Viewed 306

One of my collections in Cloud Firestore has an where each item in the array contains three separate values (see the groupMembership field: enter image description here

I know I can't write a query to find documents that match one of the array values. Is there a way to write a query to find documents that match a specific value for all three items?

For instance, I want to find all users where the groupMembership array contains one object that is equal to groupId: X, groupName: Y, membershipStatus: active

1 Answers

You can pass the entire object in an array-contains clause.

So something like:

usersRef
  .whereField("groupMembership", arrayContains: [
    "groupId": "kmDT8OUOTCxSMIBf9yZC",
    "groupName": "Jon and Charles Group",
    "membershipStatus": "pending",
  ])

The array item must completely and exactly match the dictionary you pass in. If you want to filter only on some of the properties in each array element, you will have to create additional fields with just those properties. For example, it is quite common to have say a field groupIds with just the (unique) group Ids, so that you can also filter on those (of course within the limits of Firestore's queries).

Related