skip to Main Content

The firebase flutter array cannot be searched

Please help, I haven’t found a solution for several days of searching.

FirebaseFirestore.instance
   .collection("Chats")
   .where("members", arrayContains: "90TDhef6G9QY7ljJyZjdpeaLNoA3")
   .where("members", arrayContains: "yutgffvvpobjjJyZjdpeaLNoA3")
   .get();

I want to search for a chat that contains users.

This error message appears:

You cannot use ‘array-contains’ filters more than once.

2

Answers


  1. FirebaseFirestore.instance.collection('myCollection').where('myArray', arrayContains: 'searchTerm').get().then((querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        print(doc.data());
      });
    });
    

    in this querying the "myCollection" collection and searching for documents where the "myArray" field contains the search term "searchTerm". The arrayContains operator is used to search for items in the array.

    Login or Signup to reply.
  2. As the error message and documentation on query limitations say, a Firestore query can only contain a single arrayContains operator. On your current data structure, your only option is to perform one arrayContains check in the query, and then filter the rest of it in your application code.

    To allow the query to completely run on the databae, consider storing the members in a map field rather than in an array:

    membersMap: {
      '90TDhef6G9QY7ljJyZjdpeaLNoA3': true, 
      'yutgffvvpobjjJyZjdpeaLNoA3': true
    }
    

    With this structure, you can use a == comparison to find a match, and having multiple such equality checks is allowed in a query:

    FirebaseFirestore.instance
       .collection("Chats")
       .where("membersMap.90TDhef6G9QY7ljJyZjdpeaLNoA3", isEqualTo: true)
       .where("membersMap.yutgffvvpobjjJyZjdpeaLNoA3", isEqualTo: true)
       .get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search