Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore to query by an array's field value

I'm trying to run a simple query, where I search for a document that contains a value inside an object array.

For instance, look at my database structure:

firestore db

I want to run a query similar to this:

db.collection('identites').where("partyMembers", "array-contains", {name: "John Travolta"}) 

What is the correct way to achieve this, is it even possible with Firestore?

Thanks.

like image 628
sisi mendel Avatar asked Jan 07 '19 20:01

sisi mendel


People also ask

How do I get specific data from firestore?

Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group. These queries can also be used with either get() or addSnapshotListener() , as described in Get Data and Get Realtime Updates.

What is query snapshot?

A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. The number of documents can be determined via the empty and size properties.

What is collection in firebase?

A collection contains documents and nothing else. It can't directly contain raw fields with values, and it can't contain other collections. (See Hierarchical Data for an explanation of how to structure more complex data in Cloud Firestore.) The names of documents within a collection are unique.


2 Answers

As Frank has explained in his answer it is not possible, with array-contains, to query for a specific property of an object stored in an array.

However, there is a possible workaround: it is actually possible to query for the entire object, as follows, in your case:

db.collection('identites').where("partyMembers", "array-contains", {id: "7LNK....", name: "John Travolta"}) 

Maybe this approach will suit your needs (or maybe not....).

like image 52
Renaud Tarnec Avatar answered Sep 17 '22 15:09

Renaud Tarnec


The array-contains operations checks if an array, contains a specific (complete) value. It can't check if an array of objects, contains an item with a specific value for a property.

The only way to do your query, is to add an additional field to your document with just the value you want to query existence on. So for example: partyMemberNames: ["John Travolta", "Olivia Newton"].

like image 25
Frank van Puffelen Avatar answered Sep 21 '22 15:09

Frank van Puffelen