I am using Firestore to store a Friend List for my iOS app, which is using Swift.
each document in my friends
collection has a sender
, target
, and accepted
field
when the user opens their friend list I need the app to retrieve every document where their user ID is in either the target
or sender
fields, and only where accepted == true
I know I can chain .where()
functions to create AND queries.
but as far as I can see it's not possible to do OR queries with Firestore.
Is there a way to do this in one query?
Thanks
EDIT
Here is a snapshot of the database structure
Each document is created when a friend request is sent and is then used to build the friend list for both users when required (rather than storing 2 arrays of user IDs which have to be updated separately whenever a change is made)
Update: Since early 2024 it is possible to have a query with OR conditions across multiple fields in Firestore. To learn how to create such a query and its limitations, see the Firestore documentation on queries, specifically the section on OR queries and limitations on OR queries.
For simplicity I'd probably still opt for the array membership solution that I recommended before though, so I'll leave that below for completeness:
I need the app to retrieve every document where their user ID is in either the target or sender fields
While Firestore now allows OR conditions between fields, I'd recommend an approach where your data model more closely matches the needs of your app.
If you add an array field to the document where you keep the UIDs of all participants, you can then check whether the UID you're looking for is in that array with an in
operation:
friendsRef
.whereField("participants", arrayContains: "uidOfUser")
This is essentially a more generic version of the OR-across-fields that you wanted to do, and it will likely allow more use-cases - at the cost of adding extra data to your documents. This trade-off of adding more data to (efficiently) allow a use-case is quite common when using NoSQL databases. If you're new to this, I recommend reading NoSQL data modeling techniques and watching Get to know Cloud Firestore.