[英]Can I query and retrieve Documents' field values in Subcollection in Cloud Firestore?
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
?如何查询具有英国人口的文档并检索
population
?
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.由于
Counties
子集合的名称在所有State
文档中都相同,因此要获取“British Population”属性的值,需要Firestore 集合组查询。 However, this will not work unless you have another property under your Country
document that can help you create that query.但是,除非您的
Country
文档下有另一个属性可以帮助您创建该查询,否则这将不起作用。 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".嘿 Firestore,给我所有
Countries
collections 或“国籍”为“英国”的子集合中存在的所有Country
文件。 So as you can see, I have added a new property named nationality
and added the corresponding value as "British".如您所见,我添加了一个名为
nationality
的新属性,并将相应的值添加为“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.现在,在
onSuccess()
中,您可以查询QuerySnapshot
object 并获取population
属性的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.