如何获取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屋!