Firestore search array contains for multiple values

Firestore introduced the whereIn, arrayContains and arrayContainsAny methods in late 2019. These methods perform logical 'OR' queries, but have a limit of 10 clauses you can pass in (so max 10 vitamins you can search for).

Some solutions already mentioned restructuring your data. Another solution leveraging the restructuring approach is to not include the Vitamins into the Fruit document, but the other way around. This way you get all the documents 'Banana' is part of.

let vitaminsRef = db.collection('Vitamins').where('fruits', arrayContains: 'banana');

This solution allows you to circumvent the limit of 10 clauses. It gets all the 'Vitamin' documents that have 'Banana' in their 'Fruits' array in one read operation (think about pagination, if too many).


There's no way to do multiple array-contains queries in Firestore. You can, however, combine as many where conditions as practically possible. Therefore, consider this:

[Fruits]
    <Banana>
        title: "Banana"
        vitamins:
            potassium: true
            b6: true
            c: true

Firestore.firestore().collection("Fruits").whereField("vitamins.potassium", isEqualTo: true).whereField("vitamins.b6", isEqualTo: true)

However, this still doesn't allow a clean OR search. To query for fruits with vitamin-x or vitamin-y, you'd have to get more creative. Furthermore, this approach should not be used if there are a lot of possible values and they need to be combined with compound queries. That's because Firestore does not permit more than 200 composite indices and each composite index would need to specify the exact vitamin. Which means you'd have to create an individual composite index for vitamins.b6, vitamins.potassium, etc. and you only have 200 total.


It would be tempting to to look for documents that match multiple conditions, by chaining the conditions in the query:

db.collection("Fruits")
    .whereField("vitamins", arrayContains: "B6")
    .whereField("vitamins", arrayContains: "C")

But the documentation on compound queries suggests that you cannot currently have multiple arrayContains conditions in a single query.

So, it is not possible with what you have today. Consider instead using a map structure instead of an array:

Fruits:
  Banana:
   title: "Banana"
   vitamins: {
     "potassium": true,
     "B6": true,
     "C": true
   }

Then you could query like this:

db.collection("Fruits")
    .whereField("vitamins.B6", isEqualTo: true)
    .whereField("vitamins.C", isEqualTo: true)