带驱动程序的 MongoDB
定义
db.collection.estimatedDocumentCount(options)返回集合或视图中所有文档的计数。
db.collection.estimatedDocumentCount( <options> )
参数
Parameter | 类型 | 说明 |
|---|---|---|
选项 | 文档 | 可选。影响计数行为的额外选项。 |
字段
options 文档可以包含:
字段 | 类型 | 说明 |
|---|---|---|
| 整型 | 可选。允许计数运行的最长时间。 |
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
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.
计数和事务
在事务中使用 db.collection.estimatedDocumentCount() 时,生成的计数不会过滤任何未提交的多文档事务。
例子
本页上的示例使用来自 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