20

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.

Nicholas
  • 501
  • 2
  • 14
Thiago Freitas
  • 399
  • 1
  • 4
  • 5
  • Which firebase dependency are you using? `cloud_firestore` or `firebase` on pub.dev? – Benjamin Dec 17 '19 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. ``` https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html ``` – Parth Bhanderi Dec 17 '19 at 12:51
  • According to this answer, you cannot: https://stackoverflow.com/questions/54600915/firestore-how-to-query-data-from-a-map-of-an-array – Benjamin Dec 17 '19 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 – Tax Raoul Apr 07 '21 at 12:41
  • check here https://stackoverflow.com/a/76637467/2126077 – Heshan Sandeepa Jul 07 '23 at 13:39

1 Answers1

32

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")
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807