Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore query: search in array of objects for an object with specific value (nested structure)

I have a nested structure in my Firebase and I’m trying to get the CollectionGroup of guides with specific name.

Structure looks like this:

DOCUMENT: { dives : [ {guide: { firstName: 'Jhonny' } } ] }

Image with the structure of my database is attached:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Image

My code is below:

const customerActivitiesQuery = query(collectionGroup(db, 'activities'),
where('dives', 'array-contains', { guide: { firstName: 'Johnny' } }))

Is there any chance to do this, or it is completely not possible with Firebase and I have to change the structure of my base?

>Solution :

The array-contains operator perform an exact equality check. So if your dives array contains an object that is exactly {guide: { firstName: 'Jhonny' } }, the operation will work.

The tricky bit here is that the equality check is performed on the binary gRPC data, which means that on that level it has to be the exact same value. But if they are indeed the same, the array-contains operation will work.


The more common case is that you have a subset of the fields in the array, and the array-contains operator is not made for that case.

The common workaround for that is to create an additional field with just the values you want to query on. For example:

dives_guide_firstnames: ["Jhonny"]

With that additional field, you can then query:

where('dives_guide_firstnames', 'array-contains', 'Johnny')

Note: you have a typo in Jhonny in the data structure, but I’m going to assume that is a typo in the question and not in the actual data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading