带驱动程序的 MongoDB
定义
db.collection.estimatedDocumentCount(options)返回集合或视图中所有文档的计数。
db.collection.estimatedDocumentCount( <options> )
参数
Parameter | 类型 | 说明 |
|---|---|---|
选项 | 文档 | 可选。影响计数行为的额外选项。 |
字段
options 文档可以包含:
字段 | 类型 | 说明 |
|---|---|---|
| 整型 | 可选。允许计数运行的最长时间。 |
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
机制
db.collection.estimatedDocumentCount() 不采用查询筛选器,而是使用元数据返回集合的计数。
对于视图:
没有元数据。
通过在视图定义中执行聚合管道来计算文档计数。
不存在快速估计的文档计数。
分片集群
在分片集群上,所产生的计数将无法正确剔除孤立文档。
非正常关闭
本节仅适用于集合。
非正常关闭后,计数可能不正确。
After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by db.collection.estimatedDocumentCount() may be inaccurate.
偏差的大小取决于在最后一个检查点和非正常关闭之间执行的插入、更新或删除操作的次数。检查点通常每 60 秒出现一次。但是,如果 mongod 实例使用了非默认的 --syncdelay 设置,则检查点出现的次数可能会增多或减少。
在 mongod 的每个集合上运行 validate,以在非正常关闭之后恢复统计信息。
非正常关闭后:
客户端断开连接
If the client that issued db.collection.estimatedDocumentCount() disconnects before the operation completes, MongoDB marks db.collection.estimatedDocumentCount() for termination using killOp.
计数和事务
When you use db.collection.estimatedDocumentCount() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions.
例子
本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
The following example uses db.collection.estimatedDocumentCount() to retrieve the count of all documents in the movies collection:
db.movies.estimatedDocumentCount({})
21349