Reputation: 537
Can I query and retrieve the Documents' field values in a subcollection?
Take the following for example:
States [Collection]
State 1 [Document]
Counties [Collection]
County 1 [Document]
British Population = 100 [Field]
County 2 [Document]
British Population = 200 [Field]
State 2 [Document]
Counties [Collection]
County 1 [Document]
British Population = 150 [Field]
How do I query the Documents with British Populations and retrieve the number of the population
?
Upvotes: 1
Views: 193
Reputation: 138869
Since the name of the Counties
subcollection is the same within all State
documents, to get the value of the "British Population" property, a Firestore collection group query is required. However, this will not work unless you have another property under your Country
document that can help you create that query. In code, should look like this:
db.collectionGroup("Counties").whereEqualTo("nationality", "British").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// ...
}
});
This is translated like this. Hey Firestore, give me all Country
documents that exist in all Countries
collections or subcollections where "nationality" is "British". So as you can see, I have added a new property named nationality
and added the corresponding value as "British". Since all documents do contains such property, all documents will be returned.
Besides that, the "British Population" property can also be changed to "population". Now, inside the onSuccess()
, you can query the QuerySnapshot
object and get the value for the population
property.
Upvotes: 1