【问题标题】:Can I query and retrieve Documents' field values in Subcollection in Cloud Firestore?我可以在 Cloud Firestore 的子集合中查询和检索文档的字段值吗?
【发布时间】:2020-04-25 14:24:25
【问题描述】:

我可以在子集合中查询和检索文档的字段值吗?

以以下为例:

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]

如何查询 Documents with British Populations 并检索population 的号码?

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    由于Counties 子集合的名称在所有State 文档中都相同,因此要获取“British Population”属性的值,需要Firestore collection group query。但是,除非您的 Country 文档下有另一个属性可以帮助您创建该查询,否则这将不起作用。在代码中,应该是这样的:

    db.collectionGroup("Counties").whereEqualTo("nationality", "British").get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    // ...
                }
            });
    

    这是这样翻译的。嘿 Firestore,请给我所有存在于 all Countries 集合或子集合中的所有 Country 文档,其中“国籍”为“英国”。如您所见,我添加了一个名为nationality 的新属性,并将相应的值添加为“British”。由于所有文档都包含此类属性,因此将返回所有文档。

    除此之外,“英国人口”属性也可以更改为“人口”。现在,在onSuccess() 中,您可以查询QuerySnapshot 对象并获取population 属性的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2021-05-04
      • 2018-03-31
      • 2018-06-03
      • 1970-01-01
      • 2019-12-28
      • 2018-07-07
      相关资源
      最近更新 更多