2

My use case involves filtering the Firestore documents with 'array-contains-all' whose name I made up for the purpose of this question. However, the 'array-contains-any' already exists, but it does not check whether all the elements are present in the array, but any. I struggle to find an in-built solution or find a better approach to achieve the same result rather than querying all the documents (expensive) and then filtering the result in the Cloud Function before the final array gets passed to the client.

To give an example, we are wondering which accommodation sites have all of the following facilities that we're interested in and wish to query:

[
    'lockable_bedroom_door',
    'private_bathroom',
    'internet',
    'desk',
    'safe_place_to_store_valuables'
]

out of the array of all 13 available facilities:

[
    'kettle',
    'microwave',
    'cooker',
    'washing_machine',
    'fully_functional_kitchen',
    'lockable_bedroom_door',
    'private_bathroom',
    'shared_bathroom',
    'internet',
    'desk',
    'common_room_lounge',
    'safe_place_to_store_valuables',
    'free_on-site_parking'
]

How can it be achieved with keeping in mind both the Firestore limitations and the number of facilities that the user may possibly choose?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

5

As long as you are working with list type fields as you are now, there isn't going to be a way to query that you would find efficient. If you copy the data into a new map type field, it will be possible.

facilities: {
    'kettle': true
    'microwave': true
    'cooker': true
}

With this map containing known boolean values, you can query like this:

firestore
    .collection("your-collection")
    .where("facilities.kettle", "==", true)
    .where("facilities.microwave", "==", true)
    .where("facilities.cooker", "==", true)
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    Thank you for the answer Doug! Do you know whether there is any limitation to the number of where queries with '==' operator that can be used in a single query? I have in mind possibly more than 10 facilities that a user may wish to have included in each accommodation. If not, that would be a perfect solution requiring the subtle change you outlined above. – Damian Głowala Sep 11 '20 at 19:23
  • All limits of the system are documented. If you don't see it there, then there is no known limit. https://firebase.google.com/docs/firestore/quotas – Doug Stevenson Sep 11 '20 at 19:33
  • Will this require us to configure Firestore to index the fields within `facilities`? – joshpetit Jan 06 '22 at 01:55
  • is it still the only solution? – EhsanR Aug 14 '22 at 21:25
  • 3
    this will require an index for every key under facilities .... come on firebase ... you can do better than that !!! – dsl400 Apr 03 '23 at 21:23
  • How do we add the where clauses dynamically? – Ten Digit Grid Jul 08 '23 at 19:03