How to count the number of documents under a collection in Firestore?

后端 未结 2 893
不思量自难忘°
不思量自难忘° 2020-11-22 13:43

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

FirebaseFirestore db = FirebaseFirestore.getIns         


        
相关标签:
2条回答
  • 2020-11-22 14:15

    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());
            }
        }
    });
    

    or

    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.

    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.

    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.

    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.

    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.

    0 讨论(0)
  • 2020-11-22 14:16

    inside onCompelete() check if (task.isSuccessful())before using logs. and also you can iterate over the documentSnapShot like for (DocumentSnapshot document : task.getResult()){ yourCounter++;} and increment counter on each iteration to know how many documents under collection "Posts" are available

    0 讨论(0)
提交回复
热议问题