Zhangir Siranov
Zhangir Siranov

Reputation: 479

Firestore array contains query for list of elements

I have a Firestore document that contains array like this:

Array:                    Array:
[1, 2, 3, 4, 5, 6, 7] or ['Zhangir', 'Erasyl', 'Arman']

And I need to check if this document contains any of given arrays. For Example:

[1, 2, 3, 4] or [1, 2, 7] or ['Zhangir', 'Arman'] and so on

and return it only if it has exact matches. But considering that my arrays can be 100 elements long, that would be very inconvenient to say arraycontains [1], arraycontains[2]... each time. Is there any way to do a compound query for a lot of values? All information that I found says I can't, but maybe there's a way.

From my example that would be

Firestore.instance.collection("Querys")
.where('array', arrayContains: [1, 2, 3, 4, 5]);

or

Firestore.instance.collection('Querys')
.where('array', arrayContains: ['Zhangir', 'Arman']);

and not something like

Firestore.instance.collection('Querys')
.where('array', arrayContains: 'Zhangir')
.where('array', arrayContains: 'Arman');

Upvotes: 2

Views: 8355

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

Firestore can now check for these condition on array fields:

  • Whether the field contains a specific value with array-contains.
  • Whether the field contains any of a list of (up to 10) values with array-contains-any.

What you're describing is an array-contains-all like operation, which currently doesn't exist. And you can't create it by combining multiple array-contains checks, as you can only have one of those in a query. You might want to file a feature request for it.

The best option today are to:

  1. Pick one value from the array, and perform an array-contains query with that value. Then you do the additional filtering in your application code.
  2. Use a map to store the values, and then use multiple where value == true conditions, as shown in the answer to this question: Firestore: Multiple 'array-contains'

Upvotes: 7

Related Questions