如何获取集合中文档的数量? [英] How to get count of documents in a collection?

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

问题描述

如果集合中的文档数量非常多,是否可以在不加载整个集合的情况下获取文档数.

If I have a really large number of documents in a collection, can I get the count of documents without having to load entire collection.

db.collection('largecollection').get().then(snapshot => {
   length = snapshot.size;
})

推荐答案

没有内置的API获取集合中文档数量的计数.因此,默认情况下,您将必须下载所有文档以对其进行计数.

There is no built-in API to get the count of the number of documents in a collection. So by default you'll have to download all documents to count them.

正如Renaud所评论的那样,通常的解决方法是保留一个单独的计数器,该计数器在每次添加/删除文档时都进行更新.您可以在自己的应用中执行此操作,每次通过交易更新柜台添加/删除文档的时间.但在服务器中执行此操作更为可靠,例如Cloud Functions for Firebase.有关此方法的示例,请参见 functions-samples存储库.虽然该示例适用于Firebase实时数据库,但该方法同样适用于Firestore.

As Renaud commented, the common workaround to this is to keep a separate counter that you update every time a document is added/removed. You could do this from within your app, updating the counter with a transaction every time you add/remove a document. But it's more reliable to do this in a server, such as Cloud Functions for Firebase. For an example of this approach, see the functions-samples repo. While the sample is for the Firebase Realtime Database, the approach is equally applicable to Firestore.

另请参阅分布式计数器上的"Firestore文档"部分.

Also see the Firestore documentation section on distributed counters.

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

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