Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform compound queries with logical AND on array in Cloud Firestore?

I have a collection the docs of which have an array property members which contains user IDs. I need to find the docs the members of which are a pair of user IDs, eg.:

enter image description here

From the docs for compound queries I can see how to make an OR, but I need an AND, because I need the docs that contain both user IDs (which actually is what makes a doc unique). The docs say that

you can include at most one array-contains or array-contains-any clause in a compound query

so, the following code doesn't work (I tested and it actually returns an error):

const conversation = await firebaseDb.collection(collectionName)
      .where('members', 'array-contains', userId)
      .where('members', 'array-contains', otherUserId)
      .get();

I tried this as well:

const conversation = await firebaseDb.collection(collectionName)
      .where('members', 'array-contains', [userId, otherUserId])
      .get();

but it returns nothing.

Is it actually possible to perform a logical AND on array values in a Firestore doc?

like image 998
Milkncookiez Avatar asked Sep 02 '25 06:09

Milkncookiez


1 Answers

The simplest solution I can think of is to store those IDs into a Map and not into an array. So your members Map should look like this:

members
 |
 --- M1fB...szi1: true
 |
 --- wXam...69A2: true

Now you can simply query using:

const conversation = await firebaseDb.collection(collectionName)
  .where('members.' + userId, '==', true)
  .where('members.' + otherUserId, '==', true)
  .get();

And this is indeed an AND operation.

like image 104
Alex Mamo Avatar answered Sep 04 '25 20:09

Alex Mamo