如何获取firestore集合下的文档数量?

Obe*_*lve 2 javascript firebase google-cloud-platform google-cloud-firestore

我想获取 firestore 集合中的文档总数,我正在制作一个论坛应用程序,所以我想显示每个讨论中当前的评论量。有类似的事情db.collection("comments").get().lenght或者类似的事情吗?

Ren*_*nec 12

利用size的属性QuerySnapshot,可以得到一个集合的文档数量,如下:

db.collection("comments").get().then(function(querySnapshot) {
    console.log(querySnapshot.size);
});
Run Code Online (Sandbox Code Playgroud)

但是,您应该注意,这意味着您每次想要获取文档数量时都会读取集合中的所有文档,因此,它是有成本的。

因此,如果您的集合有大量文档,则更经济的方法是维护一组保存文档数量的分布式计数器。每次添加/删除文档时,都会增加/减少计数器。

根据文档,以下是如何进行写入:

首先,初始化计数器:

  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);
Run Code Online (Sandbox Code Playgroud)

然后,在写评论的时候,使用批量写入,如下:

  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();
Run Code Online (Sandbox Code Playgroud)

对于文档删除,您可以使用以下方法减少计数器:firebase.firestore.FieldValue.increment(-1)

最后,请参阅文档如何查询计数器值!

  • 这并不完全是我所期待的,但它有效......非常感谢你。 (2认同)