gpt4 book ai didi

MongoDB count() 与 countDocuments()

转载 作者:行者123 更新时间:2023-12-03 23:59:00 30 4
gpt4 key购买 nike

我正在使用 MongoDB,更具体地说是 Mongoose。我最近已经摆脱了更新 mongo 和 mongoose 的一些弃用警告。
我的一些查询可能如下所示:

const count = await Badge.find(query).count().exec()
从那以后,我将其更改为
const count = Badge.find(query).countDocuments().exec()
和中提琴贬低警告消失了。但是,阅读 MongoDB 上的文档似乎应该这样写:
const count = Badge.countDocuments(query)
以上所有返回完全相同的东西。显然后两个是我想要的,因为 count() 的弃用。
后两个有什么区别,我应该更喜欢一个吗?

最佳答案

db.collection.find 方法返回一个游标。游标上的 cursor.count() 方法计算游标引用的文档数。这与 db.collection.count() 相同。
从 MongoDB v4.0 开始,这两种方法( cursor.count()db.collection.count() )都已弃用。从 documentation :

MongoDB drivers compatible with the 4.0 features deprecate theirrespective cursor and collection count() APIs in favor of new APIs forcountDocuments() and estimatedDocumentCount(). For the specific APInames for a given driver, see the driver documentation.


Avoid using the db.collection.count() method without a query predicatesince without the query predicate, the method returns results based onthe collection’s metadata, which may result in an approximate count.


db.collection.countDocuments(query) 返回与集合或 View 的查询匹配的文档计数。这是您需要用来计算集合中文档数量的方法。

All of the above return the exact same thing.


是的,大多数时候。只是, countDocuments 返回文档的实际计数。其他方法根据集合的元数据返回计数。
如果您想使用 db.collection.count ,请将其与查询谓词一起使用,这将返回文档的确切计数(但请注意,此方法已弃用)。

关于MongoDB count() 与 countDocuments(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65282889/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com