I want to get the total number of documents inside a firestore collection, I'm making a forum app, so I want to show the current amount of comments inside each discussion.
There's something like db.collection("comments").get().lenght
or something like that?

- 79,263
- 10
- 95
- 121

- 171
- 2
- 12
-
I think you might also be interested in this article, [How to count the number of documents in a Firestore collection?](https://medium.com/firebase-tips-tricks/how-to-count-the-number-of-documents-in-a-firestore-collection-3bd0c719978f). – Alex Mamo Jul 21 '21 at 08:11
1 Answers
With the size
property of the QuerySnapshot
, you can get the number of documents of a collection, as follows:
db.collection("comments").get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
HOWEVER, you should note that this implies that you read all the documents of the collection each time you want to get the number of documents and, therefore, it has a cost.
So, if your collection has a lot of documents, a more affordable approach would be to maintain a set of distributed counters that hold the number of documents. Each time you add/remove a document, you increase/decrease the counters.
Based on the documentation, here is how to do for a write:
First, initialize the counters:
const db = firebase.firestore();
function createCounter(ref, num_shards) {
let batch = db.batch();
// Initialize the counter document
batch.set(ref, { num_shards: num_shards });
// Initialize each shard with count=0
for (let i = 0; i < num_shards; i++) {
let shardRef = ref.collection('shards').doc(i.toString());
batch.set(shardRef, { count: 0 });
}
// Commit the write batch
return batch.commit();
}
const num_shards = 3; //For example, we take 3
const ref = db.collection('commentCounters').doc('c'); //For example
createCounter(ref, num_shards);
Then, when you write a comment, use a batched write as follows:
const num_shards = 3;
const ref = db.collection('commentCounters').doc('c');
let batch = db.batch();
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = ref.collection('shards').doc(shard_id);
const commentRef = db.collection('comments').doc('comment');
batch.set(commentRef, { title: 'Comment title' });
batch.update(shard_ref, {
count: firebase.firestore.FieldValue.increment(1),
});
batch.commit();
For a document deletion you would decrement the counters, by using: firebase.firestore.FieldValue.increment(-1)
Finally, see in the doc how to query the counter value!

- 79,263
- 10
- 95
- 121
-
2This wasn't exactly what I was expecting, but it worked... Thanks you very much. – Obed Monsalve Apr 16 '20 at 15:43
-
Note that the issue of counting documents is very well discussed in a duplicate. If you have additional information, please add it there. – Doug Stevenson Apr 16 '20 at 16:04