如何计算Firestore中集合下的文档数量? [英] How to count the number of documents under a collection in Firestore?

查看:152
本文介绍了如何计算Firestore中集合下的文档数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 CollectionReference 计算Cloud Firestore上存在的数量,我试图使用它:

I am trying to get CollectionReference count that exists on the Cloud Firestore, I have tried to get it with:

FirebaseFirestore db = FirebaseFirestore.getInstance();
    final CollectionReference postsCollection = db.collection("Posts");

    final TaskCompletionSource<Integer> source = new TaskCompletionSource<>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            int fromWhereToStart = postsCollection.get().getResult().size();
            source.setResult(fromWhereToStart);
        }
    }).start();

    Task<Integer> task = source.getTask();
    task.addOnCompleteListener(new OnCompleteListener<Integer>() {
        @Override
        public void onComplete(@NonNull Task<Integer> task) {
            Log.e("Z_fromWhereToStart", "= " + task.getResult());
        }
    });

但遗憾的是,我收到了:

But unfortunately, I'm getting:

java.lang.IllegalStateException: Task is not yet complete

是否有另一种方法来计算另一种方法来修复 IllegalStateException

Is there is another way to get the count of another way to fix the IllegalStateException?

推荐答案

我们在Firebase实时数据库中没有 getDocumentCount()方法, getChildrenCount()方法,要实际计算您的Cloud Firestore中帖子集合下面的所有文档的数量,请使用以下代码:

Becasue there is no getDocumentCount() method as we have in Firebase Realtime database, a getChildrenCount() method, to actually count the number of all documents beneath your Posts collection from your Cloud Firestore, please use the following code:

db.collection("Posts").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            int count = 0;
            for (DocumentSnapshot document : task.getResult()) {
                count++;
            }
            Log.d("TAG", count + "");
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

db.collection("Posts").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", task.getResult().size() + "");
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

以上示例适用于小型数据集,但如果数据集较大则不起作用。但是,还有两种方法可以实现同样的目的。

The above examples work well enough for small datasets but it doesn't work if the datasete is larger. But, there are also two more ways in which you can achieve the same thing.

一种方法是使用云功能都会更新计数器 $ c>帖子收藏。这个技术也适用于大数据集。但请注意,在这种情况下,文档的添加和删除只能以小于或等于每秒1的速率发生,如 Cloud Firestore配额和限制。这是一个要阅读的单个文档,但它几乎立即显示当前计数。

One way would be to use Cloud Functions to update a counter every time you add or delete a document from the your Posts collection. This tehnique works well also for big datasets. But note, in this case, the additions and deletions of documetns can only occur at the rate less than or equal to 1 per second, as described in Cloud Firestore Quotas and Limits. That is a single document to read but it shows you the current count almost instantly.

如果您需要超出此限制,则需要实现分布式计数器,如官方文档中所述分布式计数器

If there is a need for you to exceed this limitation, you need to implement distributed counters as explained in the official documentation of distributed counters.


作为个人提示,请勿在Cloud Firestore中存储此类计数器,因为每次都是增加或减少计数器将花费您操作。在 Firebase Realtime 数据库免费中托管此计数器。

As a personal hint, don't store this kind of counters in Cloud Firestore, because every time you increase or decrease the counter will cost you a read or a write operation. Host this counter in Firebase Realtime database at no cost.

第二种方式是,而不是使用云功能,在客户端使用事务,在添加或删除文档的同时更新计数器。这样,您的计数器也将是准确的,因为它会同时更新。但在这种情况下最重要的是,您需要确保在添加或删除文档的任何位置包含此逻辑。您可以在这种情况下使用Firebase实时数据库免费使用。

The second way would be, rather than using Cloud Functions, to use transactions at your client side, to update the counter at the same time as you add or delete a document. In this way, your counter will also be accurate, because it is updated at the same time. But the most important thing in this case is that you'll need to make sure to include this logic anywhere you add or delete a document. You can use in this case Firebase Realtime database as weel, at no cost.

作为结论,使用第一个代码用于小数据集,第二个使用Cloud Functions因为是写的 - 尽力而为,第三次使用我上面解释过的最后一个选项。

As a conclusion, use the first code for small datasets, second use Cloud Functions because is write-time best-effort and third use the last option I have explained you above.

这篇关于如何计算Firestore中集合下的文档数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆