【问题标题】:How to get a count of the number of documents and the id's of these, in a collection with Cloud Firestore如何在 Cloud Firestore 的集合中计算文档数量和这些文档的 ID
【发布时间】:2018-12-16 17:44:58
【问题描述】:

在 Firestore 中,如何获取集合中的文档总数和这些文档的 ID?

例如,如果我有

/Usuarios
    /Cliente
        /JORGE
            /456789
                /filtros
                      /status
                          /activo
                          /inactivo

我的代码:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<QuerySnapshot> docRef = db.collection("Usuarios").document("Cliente").collection("JORGE").document("filtros").collection("status").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            int contador = 0;
                            for (DocumentSnapshot document: task.getResult()) {
                                contador++;
                            }

                            int cantPS = contador;
}

我想查询我有多少人和得到:2 和 id 的:activo, inactivo。

【问题讨论】:

  • 也请查看this

标签: android firebase google-cloud-firestore


【解决方案1】:

要确定查询返回的文档数,请使用QuerySnapshot.size()

要获取查询返回的文档列表,请使用QuerySnapshot.getDocuments()

要显示文档的键,请使用DocumentSnapshot.getId()

总之:

public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if (task.isSuccessful()) {
        QuerySnapshot querySnapshot = task.getResult();
        int count = querySnapshot.size();
        System.out.println(count);
        for (DocumentSnapshot document: querySnapshot.getDocuments()) {
            System.out.println(document.getId());
        }
    }
}

【讨论】:

  • 感谢您的帮助!但这在应用程序中返回 0。我正在做的是使用具有特定集合的文档数量动态创建按钮,并且在应用 Firestore 提供的“CollectionRefence”功能时,它必须更改为:Task 因为如果所有代码功能错误
  • 当您运行此代码时,应记录文档,后跟每个单独的文档 ID。如果它记录 0,则集合中没有文档。
  • 你说得对,我的朋友,还有一些领域可以识别它们。这会一直伴随着我,我才刚刚开始进入 firebase 的世界。非常感谢您的帮助。
猜你喜欢
  • 2019-11-13
  • 2018-07-10
  • 2018-04-14
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多