如何获取firestore集合下的文档数量? [英] How to get the number of documents under a firestore collection?
问题描述
我想获取 firestore 集合中的文档总数,我正在制作一个论坛应用程序,所以我想在每个讨论中显示当前的评论数量.有类似 db.collection("comments").get().lenght
之类的东西吗?
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?
推荐答案
使用 size
属性nofollow noreferrer">QuerySnapshot
,可以得到一个集合的文档数,如下:
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:
首先,初始化计数器:
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();
对于文档删除,您可以使用以下方法减少计数器:firebase.firestore.FieldValue.increment(-1)
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!
这篇关于如何获取firestore集合下的文档数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!