How To Get The Number Of Documents Under A Firestore Collection?
Solution 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=0for (let i = 0; i < num_shards; i++) {
let shardRef = ref.collection('shards').doc(i.toString());
batch.set(shardRef, { count: 0 });
}
// Commit the write batchreturn batch.commit();
}
const num_shards = 3; //For example, we take 3constref = 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;
constref = 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!
Post a Comment for "How To Get The Number Of Documents Under A Firestore Collection?"