2

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?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Obed Monsalve
  • 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 Answers1

12

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!

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121