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

奥贝德蒙萨韦

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

雷诺塔内克

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

db.collection("comments").get().then(function(querySnapshot) {
    console.log(querySnapshot.size);
});

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

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

根据文档,这里是写操作的方法:

首先,初始化计数器:

  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);

然后,当你写评论时,使用如下批量写入:

  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();

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

最后,在文档中查看如何查询计数器值!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Cloud Firestore获取集合中文档的数量

如何在不读取文档的情况下提前获取文档数量-Firestore-Swift

如何获取firestore集合中的文档数

如何计算Firestore中某个集合下的文档数?

Firestore-获取文档集合

SwiftUI:如何迭代 Cloud Firestore 集合中的文档并获取数据?

如何从Firestore上的文档获取所有集合ID?

如何从不同集合的文档中获取 Firestore 数据

Firestore - 如何从集合中获取文档的 ID?安卓Java

Firestore:如何在集合中获取随机文档

如何从Firestore中快速获取集合中的文档ID

如何从Firestore中的集合的特定文档获取所有密钥?

如何获取集合Cloud Firestore中的文档ID列表?

如何使用Flutter从Firestore中的集合中获取特定文档

如何从 Firestore 集合中的文档中获取数据?

如何获取Firestore集合中所有文档的名称(字段)?

如何根据索引从 Cloud Firestore 集合中获取文档?

如何通过文档 ID 获取 Firestore 集合快照

如何获取集合>文档>集合>文档中的firestore数据库中的字段?

获取Mongodb集合中文档数量的计数

如何在集合中获取文档ID的列表而不在Firestore中获取文档的内容?

如何在Cloud Firestore中高效地获取集合及其子集合的所有文档

Firestore从集合中获取文档ID

查询 FireStore 集合以获取文档密钥

Swift firestore 同时获取多个集合的文档?

如何从Firestore中的文档ID数组中获取所有子集合文档

如何在 Firebase Firestore 的每个文档的子集合中获取文档?

Elasticsearch Java API-如何在不检索文档的情况下获取文档数量

如何使用模块化 Web SDK 的版本 9 在 Cloud Firestore 集合中的文档中获取文档和嵌套集合?