是否可以使用新的Firebase数据库Cloud Firestore来计算一个集合有多少项?

如果是,我该怎么做?


当前回答

目前,firebase只允许服务器端计数,如下所示

const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);

请不要,这是为nodeJS

其他回答

FireStore现在支持该功能,尽管是Beta版。 下面是Firebase的官方文档

根据上面的一些答案,我花了一段时间才让它工作,所以我想把它分享给其他人使用。希望对大家有用。

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.countDocumentsChange = functions.firestore.document('library/{categoryId}/documents/{documentId}').onWrite((change, context) => {

    const categoryId = context.params.categoryId;
    const categoryRef = db.collection('library').doc(categoryId)
    let FieldValue = require('firebase-admin').firestore.FieldValue;

    if (!change.before.exists) {

        // new document created : add one to count
        categoryRef.update({numberOfDocs: FieldValue.increment(1)});
        console.log("%s numberOfDocs incremented by 1", categoryId);

    } else if (change.before.exists && change.after.exists) {

        // updating existing document : Do nothing

    } else if (!change.after.exists) {

        // deleting document : subtract one from count
        categoryRef.update({numberOfDocs: FieldValue.increment(-1)});
        console.log("%s numberOfDocs decremented by 1", categoryId);

    }

    return 0;
});

聚合计数查询刚刚在Firestore中预览。

在2022年Firebase峰会上宣布:https://firebase.blog/posts/2022/10/whats-new-at-Firebase-Sumit-2022

摘录:

[开发人员预览]Count()函数:与新的计数函数 Firstore[原文],你现在可以得到匹配文件的计数当你 运行查询或从集合中读取,而不加载实际的 文件,这为你节省了很多时间。

他们在峰会上展示的代码示例:

在问答环节中,有人问了汇总查询的定价问题,Firebase团队给出的答案是,它的成本是读取价格的1 / 1000(四舍四入到最近的读取,详情见下面的评论),但将计算汇总的所有记录。

没有直接的选择。不能执行db.collection("CollectionName").count()。 下面是查找集合中文档数量的两种方法。

1:-得到集合中的所有文件,然后得到它的大小。(不是最好的解决方案)

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

通过使用上述代码,您的文档读取的大小将等于集合中的文档大小,这就是为什么必须避免使用上述解决方案的原因。

2:-创建一个单独的文档与在您的集合,将存储在集合中的文件的数量计数。(最佳解决方案)

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

上面我们创建了一个带有名称计数的文档来存储所有计数信息。您可以通过以下方式更新计数文档:—

在文档计数上创建一个触发器 在创建新文档时,增加counts文档的count属性。 删除文档时,递减counts文档的count属性。

w.r.t价格(文档读取= 1)和快速数据检索上述解决方案是很好的。

firebaseFirestore.collection("...").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            int Counter = documentSnapshots.size();

        }
    });