有没有一种查询Firestore集合的方法来获取字段值出现的次数? [英] Is there a way to query for a Firestore collection to get the number of times a field's value occurs?

查看:44
本文介绍了有没有一种查询Firestore集合的方法来获取字段值出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是以以下方式查询集合:
1.我可以得到所有文档中 true 值出现的次数

What I am trying to do is to query a Collection in such a way that:
1. I can get the number of times the value true occurs in all documents

就像,有没有一种方法可以检查每个文档并查询匹配 true 的文档字段?

Like, is there a way to check through each document and query for document fields matching true ?

  1. 之后,将 true 值出现在变量中的次数存储.
  1. After that, store the number of times that true value occurs in a variable.

推荐答案

有多种可能的方法:

您可以编写查询,该查询将返回所有文档并使用size 属性.firestore.QuerySnapshot.html"rel =" nofollow noreferrer> QuerySnapshot :

You can write a query that will return all the documents and use the size property of the QuerySnapshot:

db.collection("Londiani Hill").where("TransmitterError", "==", true)
    .get()
    .then(function(querySnapshot) {
        console.log(querySnapshot.size);
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

这种方法的问题是,每次要计数它们时,您都会使用 TransmitterError = true 字段读取所有文档,并且这是有成本的.

The problem with this approach is that you read all the documents with a field TransmitterError = true each time you want to count them and this has a cost.

每次创建带有字段 TransmitterError = true 的文档时,您都可以增加一个计数器(如果删除文档或将 TransmitterError 的值更改为 false ).您需要为每个集合维护一个计数器.

You can increment a counter each time you create a document with field TransmitterError = true (and decrement it if you delete the doc or change the value of TransmitterError to false). You will need to maintain one counter per collection.

要实现计数器,您可以为每个集合使用分布式计数器或使用一个计数器"每个集合的文档,如果您有一个使用 firebase.firestore.FieldValue.increment()递增的计数器字段,请参见

For implementing the counter you can either use a Distributed counter per collection OR use one "counter" document per collection where you have a counter field that you increment with firebase.firestore.FieldValue.increment(), see the doc.

两种类型的计数器之间的选择标准是特定集合的计数器将被更新的次数:事实上,在Cloud Firestore中,您只能大约更新一次文档每秒.因此,如果您知道计数器的文档每秒可能更新一次以上,则应选择分布式计数器的方法,否则,每个集合可以依靠一个计数器文档.

The selection criteria between the two types of the counter is the number of times a counter for a specific collection will be updated: as a matter of fact, in Cloud Firestore, you can only update a single document about once per second. So if you know that counter's documents might be updated more than once per second, you should choose the distributed counters approach, otherwise, you can rely on one counter document per collection.

这篇关于有没有一种查询Firestore集合的方法来获取字段值出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆