Cloud Firestore collection count

后端 未结 17 1525
庸人自扰
庸人自扰 2020-11-22 09:25

Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

If so, how do I do that?

17条回答
  •  醉梦人生
    2020-11-22 09:50

    There is no direct option available. You cant't do db.collection("CollectionName").count(). Below are the two ways by which you can find the count of number of documents within a collection.

    1 :- Get all the documents in the collection and then get it's size.(Not the best Solution)

    db.collection("CollectionName").get().subscribe(doc=>{
    console.log(doc.size)
    })
    

    By using above code your document reads will be equal to the size of documents within a collection and that is the reason why one must avoid using above solution.

    2:- Create a separate document with in your collection which will store the count of number of documents in the collection.(Best Solution)

    db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
    console.log(doc.count)
    })
    

    Above we created a document with name counts to store all the count information.You can update the count document in the following way:-

    • Create a firestore triggers on the document counts
    • Increment the count property of counts document when a new document is created.
    • Decrement the count property of counts document when a document is deleted.

    w.r.t price (Document Read = 1) and fast data retrieval the above solution is good.

提交回复
热议问题