如何获取具有Cloud Firestore的集合中的文档数量 [英] How to get a count of number of documents in a collection with Cloud Firestore

查看:101
本文介绍了如何获取具有Cloud Firestore的集合中的文档数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Firestore中,如何获取集合中的文档总数?例如,如果我有
$ b $
b

  / people 
/ 123456
/ name - 'John'
/ 456789
/ name - 'Jane'

我想查询我有多少人,并获得2个。



我可以在/ people上查询,然后得到返回结果的长度,但这似乎是一种浪费,尤其是因为我将在较大的数据集上执行此操作。



选项1:客户端



这基本上是你提到的方法。从集合中选择所有,并在客户端计数。这对于小数据集来说已经足够了,但是如果数据集数据量大的话,显然是行不通的。选项2:写入时间最好的努力

使用这种方法,您可以使用云端函数为集合中的每个添加和删除更新计数器。



这适用于任何数据集的大小,只要添加/删除的速率小于或等于每秒1次。这给你一个单一的文件读取立即给你几乎当前的计数。

如果需要每秒超过1,你需要根据我们的文档实施分发的计数器



选项3:准确写入时间



与您使用云端函数不同,您可以在客户端更新计数器,删除一个文件。这意味着计数器也将是我们目前的,但你需要确保添加或删除包括这个逻辑的任何地方。



像选项2,你需要如果你想超过每秒
,实施分布式计数器

In Firestore, how can I get the total number of documents in a collection?

For instance if I have

/people
    /123456
        /name - 'John'
    /456789
        /name - 'Jane'

I want to query how many people I have and get 2.

I could do a query on /people and then get the length of the returned results, but that seems a waste, especially because I will be doing this on larger datasets.

解决方案

You currently have 3 options:

Option 1: Client side

This is basically the approach you mentioned. Select all from collection and count on the client side. This works well enough for small datasets but obviously doesn't work if the dataset is larger.

Option 2: Write-time best-effort

With this approach, you can use Cloud Functions to update a counter for each addition and deletion from the collection.

This works well for any dataset size, as long as additions/deletions only occur at the rate less than or equal to 1 per second. This gives you a single document to read to give you the almost current count immediately.

If need need to exceed 1 per second, you need to implement distributed counters per our documentation.

Option 3: Write-time exact

Rather than using Cloud Functions, in your client you can update the counter at the same time as you add or delete a document. This means the counter will also we current, but you'll need to make sure anywhere that adds or deletes includes this logic.

Like option 2, you'll need to implement distributed counters if you want to exceed per second

这篇关于如何获取具有Cloud Firestore的集合中的文档数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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