mongodb - MongoDB中count()和find().count()的区别

有什么区别,我基本上是想找到mycollection中的所有文档。 db.mycollection.count() vs db.mycollection.find().count()?

它们都返回相同的结果。有什么理由为什么有人会选择 count()find().count()?相比之下,find() 应用了默认限制(如果我错了,请纠正我),您必须输入“it”才能在 shell 中看到更多内容。

最佳答案

db.collection.count()cursor.count() 只是 count 的包装。命令因此运行 db.collection.count()cursor.count() 有/没有相同将返回相同的 query 参数,将返回相同的结果。但是 count 结果可以是 inaccurate in sharded cluster .

MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection count() APIs in favor of new APIs for countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver documentation.

db.collection.countDocuments方法内部使用 aggregation query在 db.collection.estimatedDocumentCount/ 时返回文档计数根据元数据返回文档计数。

值得一提的是,estimatedDocumentCount 输出可能不准确,如 documentation 中所述。 .

https://stackoverflow.com/questions/32666330/

相关文章:

python - 如何检查 MongoDB 实例的客户端是否有效?

python - 为什么 PyMongo 3 给出 ServerSelectionTimeoutEr

mongodb - 在 MongoDB 中存储 ObjectId 及其字符串形式之间的区别

node.js - 未找到匹配项的 Mongoose 查询返回什么?

mongodb - Mongo复杂排序?

node.js - 具有一对多关系的 Mongoose 文档引用

mongodb - 如何获取 MongoDB 中单个索引的大小?

mongodb - Mongo ids 导致可怕的 URL

node.js - 为什么MongoDB Node Driver生成实例池被破坏错误?

mongodb - 获取文档的特定部分