How to get the number of documents under a firestore collection? [duplicate]

☆樱花仙子☆ 提交于 2020-04-30 08:24:39

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/61250180/how-to-get-the-number-of-documents-under-a-firestore-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!