2

I have a firestore collection where each document has a collection of strings 'tags', I'd like to do a query to the firestore collection and get all results where a string appears in the tags array.

Something like:

 var { docs } = await admin
            .firestore()
            .collection('submissions')
            .where((x)=> x.tags.contains('mytag'))
            .get();

Is that possible?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
meds
  • 21,699
  • 37
  • 163
  • 314
  • firestore now supports array contains. More info here => https://firebase.google.com/support/release-notes/js – Adarsh Aug 10 '18 at 16:13

1 Answers1

3

You can't (yet) query for items where an array contains a certain value. See the Firestore documentation on working with arrays, lists, and sets, which recommends that you instead model your tags as:

tags: {
  mytag: true,
  myothertag: true
}

And then query it with:

db.collection('submissions')
    .where('tags.mytag', '==', true)
    .get()
    .then(() => {
        // ...
    });
)

I also recommend that you read my answer to Firebase query if child of child contains a value, which contains another example. While it is for the Firebase Realtime Database, the same logic applies here.

There is work being done to allow querying an array for a value as you are doing. But as usual: no promises on when this will be available, so keep an eye out on the release notes for Firestore updates.

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