22

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.

5
  • Which firebase dependency are you using? cloud_firestore or firebase on pub.dev? Commented Dec 17, 2019 at 12:43
  • I think you can't querying key value type array contains in cloud firebase you have to filter that data on client side. ``` firebase.googleblog.com/2018/08/… ``` Commented Dec 17, 2019 at 12:51
  • According to this answer, you cannot: stackoverflow.com/questions/54600915/… Commented Dec 17, 2019 at 12:52
  • I have this exact structure and i thought it would be easy, but its seems there is no way to perform this query in firestore. What would be the best way to achieve this in the client side? thanks for any suggestion Commented Apr 7, 2021 at 12:41
  • check here stackoverflow.com/a/76637467/2126077 Commented Jul 7, 2023 at 13:39

1 Answer 1

36

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")
Sign up to request clarification or add additional context in comments.

3 Comments

You seem to be missing a double quote (") on the first code block.
Thanks for flagging. Feel free to fix it next time you spot something like that.
@FrankvanPuffelen thank you, i undestand, i need create node of array with all acocuntIds. thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.