Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - query where filter of object in array field

I have question about query in firecloud.

For example, see my document:

document

i need filter all documents where the account_id is "value" and "approve" is true. How i do it?

I tried: where("members.account_id", "==, "qgZ564nfEaNP3Nt4cW1K3jCeVlY2") and not work:

See, this is a question that not for specific language, just about firestore query, after undestand, i go apply it in my code.

I'm programing in flutter.

like image 844
Thiago Freitas Avatar asked Dec 17 '19 12:12

Thiago Freitas


People also ask

How do you query collections in firestore under a certain path?

There is no way to get documents from different collections or sub-collections in a single query. Firestore doesn't support queries across different collections in one go unless we are using a collection group query.

Are arrays indexed in firestore?

Automatic indexing For each map field, Cloud Firestore creates one collection-scope ascending index and one descending index for each non-array and non-map subfield in the map. For each array field in a document, Cloud Firestore creates and maintains a collection-scope array-contains index.

What is querySnapshot in firebase?

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.


1 Answers

If you query like this:

where("members.account_id", "==", "qgZ564nfEaNP3Nt4cW1K3jCeVlY2")

Firebase checks if there's a nested field /members/account_id with the given value. And such a field doesn't exist, because the value is actually at /members/0/account_id.

Since you don't know the position in the array the the ID exists, you instead want to use an array-contains condition. With array-contains Firestore checks if the array you contains the exact member that you specify.

With your current structure you can check if the member exists with:

.where("members", "array-contains", { accountId: "qgZ564nfEaNP3Nt4cW1K3jCeVlY2", approved: true })

So you must know the entire data of the array element in order to use array-contains.

If you only know a single member, while you're storing multiple members, you can't use array-contains. In that case, I recommend adding an additional member_accountIds field to each document, where you store just their account IDs:

member_accountIds: ["qgZ564nfEaNP3Nt4cW1K3jCeVlY2", ... ]

With that in place, you can query like this:

.where("members_accountIds", "array-contains", "qgZ564nfEaNP3Nt4cW1K3jCeVlY2")
like image 110
Frank van Puffelen Avatar answered Oct 20 '22 06:10

Frank van Puffelen