MongoDB 中 count() 和 find().count() 的区别 [英] Difference between count() and find().count() in MongoDB

查看:75
本文介绍了MongoDB 中 count() 和 find().count() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别,我基本上是想把mycollection里面的所有文档都找一下.db.mycollection.count() 对比db.mycollection.find().count()?

What is the difference between, I basically wanted to find all the documents in the mycollection. db.mycollection.count() vs db.mycollection.find().count()?

它们都返回相同的结果.有人会选择 count() 还是 find().count() 有什么理由吗?与 find() 应用了默认限制(如果我错了,请纠正我)的事实相反,您必须输入it"才能在 shell 中看到更多内容.

They both returns the same result. Is there any reason why would somebody choose the count() vs the find().count()? In contrast to the fact that find() has a default limit applied (correct me if I'm wrong) to which you would have to type "it" in order to see more in the shell.

推荐答案

db.collection.count()cursor.count() 只是 cursor.count() 的包装器一个 href="https://docs.mongodb.com/manual/reference/command/count/" rel="nofollow noreferrer">count 命令从而运行 db.collection.count()cursor.count() 有/没有相同将返回相同的 query 参数,将返回相同的结果.但是 count 结果在分片集群中可能是 不准确.

db.collection.count() and cursor.count() are simply wrappers around the count command thus running db.collection.count() and cursor.count() with/without the same will return the same query argument, will return the same result. However the count result can be inaccurate in sharded cluster.

与 4.0 特性兼容的 MongoDB 驱动程序弃用了它们各自的游标和集合 count() API 支持新的 APIcountDocuments() 和estimatedDocumentCount().对于特定的 API给定驱动程序的名称,请参阅驱动程序文档.

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 方法在内部使用 聚合查询 返回文档计数,而 db.collection.estimatedDocumentCount/ 根据元数据返回文档计数.

The db.collection.countDocuments method internally uses an aggregation query to return the document count while db.collection.estimatedDocumentCount/ returns documents count based on metadata.

值得一提的是,estimatedDocumentCount 输出可能不准确,如文档.

It is worth mentioning that the estimatedDocumentCount output can be inaccurate as mentioned in the documentation.

这篇关于MongoDB 中 count() 和 find().count() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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