I have question about query in firecloud.
For example, see my 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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With