Counting Documents in a Firestore Collection
Edit: October 20th, 2022
Firestore now provides a count() method that counts the documents in a collection or the documents returned by a query without reading the documents. This eliminates the need for maintaining a counter.
Query query = db.collection("Posts").orderBy("createdAt"); Task<Long> task = query.count(); task.addOnCompleteListener(new OnCompleteListener<Long>() { @Override public void onComplete(@NonNull Task<Long> task) { long count = task.getResult(); } });
Edit: July 10th, 2021
Firebase introduces the Distributed Counter Extension, which provides a highly scalable counter service for high-velocity actions like views, likes, or shares. This extension allows counting operations to exceed the limitation of one write operation per second.
Original Answer:
Retrieving Count of Documents Without getDocumentCount() Method
Since Firestore lacks a dedicated getDocumentCount() method, alternative approaches are necessary to count the number of documents in a collection.
db.collection("Posts").get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { int count = task.getResult().size(); Log.d(" TAG", count + "" ); } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } });
Limitations and Alternatives
This approach is suitable for small datasets. For larger datasets, consider alternative methods:
The above is the detailed content of How Can I Efficiently Count Documents in a Firestore Collection?. For more information, please follow other related articles on the PHP Chinese website!