skip to Main Content

Assuming I have documents in the Firestore in the following format:

{
    'field1': ['v1', 'v2', 'v3'],
    'field2': ['v5', 'v6']
}

I want to query for the documents where the field1 contains a value from the given values, and the field2 contains a given value. I want to perform an AND operation where I specify these conditions in a single query only and get all the valid documents. Following is what I tried:

await FirebaseFirestore.instance
        .collection(COLLECTION)
        .where("field1", arrayContainsAny: ['v1', 'v2'])
        .where('field2', arrayContains: 'v1')
        .get();

But I got an exception:

enter image description here

So Is there any way to combine these to make a query?

2

Answers


  1. So is there any way to combine these to make a query?

    No, you cannot combine arrayContainsAny and arrayContains in the same query. According to the official documentation regarding array membership:

    You can use at most one array-contains clause per disjunction (or group). You can’t combine array-contains with array-contains-any in the same disjunction.

    To solve this, you should use one of the conditions in the query and filter the rest of the results on the client.

    Login or Signup to reply.
  2. If the two Arrays are not too large (Maximum size for a document is 1 MiB) you could create a new field that combines both Arrays as follows:

    const field1 = ['v1', 'v2', 'v3'],
        field2 = ['v5', 'v6'],
        combinedField = [];
    
    field1.forEach(elemArray1 => {
      field2.forEach(elemArray2 => {
        combinedField.push('${elemArray1}_${elemArray2}');
      });
    });
    
    // combinedField = ['v1_v5', 'v1_v6', 'v2_v5', 'v2_v6', 'v3_v5', 'v3_v6']
    

    and then use the following query:

    await FirebaseFirestore.instance
            .collection(COLLECTION)
            .where("combinedField", arrayContainsAny: ['v1_v5', 'v2_v5'])
            .get();
    

    Note that the arrays values should not contain the separator, _ in this example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search