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

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

问题描述

在 Firestore 中,如何获取集合中的文档总数?

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

例如如果我有

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

我想查询我有多少人并得到 2 个.

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

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

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.

推荐答案

您目前有 3 个选项:

You currently have 3 options:

这基本上就是你提到的方法.从集合中选择所有并在客户端计数.这对于小数据集来说效果很好,但如果数据集较大,显然就行不通了.

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.

通过这种方法,您可以使用 Cloud Functions 为集合中的每次添加和删除更新计数器.

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

这适用于任何数据集大小,只要添加/删除的速度小于或等于每秒 1 次.这为您提供了一个可供阅读的文档,以便立即为您提供几乎当前的计数.

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.

如果需要超过每秒 1 个,您需要根据我们的文档实施 分布式计数器.

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

在您的客户端中,您可以在添加或删除文档的同时更新计数器,而不是使用 Cloud Functions.这意味着计数器也将是最新的,但您需要确保在添加或删除文档的任何位置都包含此逻辑.

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 be current, but you'll need to make sure to include this logic anywhere you add or delete documents.

与选项 2 一样,如果您想超过每秒,则需要实现分布式计数器

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

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

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