How do I query Cloud Firestore for an array that matches all values, but in any order?

Viewed 264

I have an array in Firestore in different documents like this:

Colors: [Blue, Red, Green]

I want to query to find the documents that matches my input, Colors: [Red, Green, Blue]. But it should NOT return documents that contain more than that, i.e. [Blue, Red, Green, Yellow]. It has to be an exact match, but I do not necessarily know the order of the items in the array. Is this even possible?

2 Answers

First, add a field to each document that contains the array length so that you can filter based on the array length. Then create a compound query for arrays with the correct length, with an "array-contains" clause for each color.

Note that the particular array you are searching for must not contain any duplicate elements or this method will not work correctly.

What you're asking is not possible with a single query with the data you have now. You will either have to:

  1. Ensure the order of the array so you can use an equality filter providing an array that contains the exact same data.
  2. Rewrite the array to a map, so you could instead use an equality filter for the same set of key/value pairs. (The keys could be the colors, and the values could simply be boolean true.)
Related