Thiago Freitas
Thiago Freitas

Reputation: 419

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.

Upvotes: 21

Views: 13692

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599581

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")

Upvotes: 35

Related Questions