3

I am trying to add an OR condition to my flutter firebase query.

Here is my code but I want to check where receiver_name is equal to kim OR sender_name is equal to kim

StreamBuilder( 
  stream: Firestore.instance.collection("payments").where("receiver_name", isEqualTo: userActive).snapshots(),
  builder: (context, snapshot){
 

  return Container ( child:ListView.builder(
      shrinkWrap: true,
    itemCount: snapshot.data.documents.length,
    padding: EdgeInsets.all(0),
    controller: ScrollController(keepScrollOffset: false),
    itemBuilder: (context, index){

      DocumentSnapshot documentSnapshot = snapshot.data.documents[index];
                                        
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
mac
  • 131
  • 1
  • 7
  • 1
    I don't see a way to do this natively with the `cloud_firestore` package. You probably have to do 2 separate queries and you can combine the streams. – Christopher Moore Jul 25 '20 at 18:57
  • Thanks, I see, how do I go about combining streams after I got them?if you don't mind me asking – mac Jul 25 '20 at 19:13
  • You can either follow one of the answers [here](https://stackoverflow.com/questions/51214217/combine-streams-from-firestore-in-flutter)(probably the highest voted one, not the accepted) or maybe follow instructions [here](https://dart.dev/articles/libraries/creating-streams) to create/transform a stream – Christopher Moore Jul 25 '20 at 19:17

1 Answers1

5

As @ChristopherMoore commented, OR conditions on multiple fields are not possible with Firestore. Executing a separate query and merging them client-side is the most common workaround. For more on this see:

The reason for not marking your question as a duplicate of those, is to point out another way to accomplish the same result with a single query.


Add an array of participants to each document

If you add an array field participants to your documents, with in it the UID fields of the sender and the receiver, you can then use an array-contains query to get all payments in which the user was either the sender or the receiver.

To add a UID to such an array, be sure to use the array-union operator:

documentRef.updateData({"participants": FieldValue.arrayUnion("uidOfUser")});

And then to query it, you'd use:

collectionRef.where('participants', arrayContains: "uidOfUser")
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734