Docs HomeMongoDB Manual

db.collection.countDocuments()

Definition定义

db.collection.countDocuments(query, options)
Important

mongosh Method

This page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.

For the database command, see the $group aggregation stage and the $sum expression called by the aggregate command.

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

mongo shell v4.4

Returns an integer for the number of documents that match the query of the collection or view. 返回一个整数,表示与集合或视图的查询匹配的文档数。This method is available for use in Transactions.此方法可用于事务处理。

db.collection.countDocuments( <query>, <options> )
Parameter参数Type类型Description描述
querydocumentThe query selection criteria. 查询选择条件。To count all documents, specify an empty document. 若要统计所有文档,请指定一个空文档。See also Query Restrictions.另请参见查询限制
optionsdocumentOptional.可选的。Extra options that affects the count behavior.影响计数行为的额外选项。

The options document can contain the following:options文档可以包含以下内容:

Field字段Type类型Description描述
limitintegerOptional.可选的。The maximum number of documents to count.要计数的最大文档数。
skipintegerOptional.可选的。The number of documents to skip before counting.计数前要跳过的文档数。
hintstring or documentOptional.可选的。An index name or the index specification to use for the query.用于查询的索引名称或索引规范。
maxTimeMSintegerOptional.可选的。The maximum amount of time to allow the count to run.允许运行计数的最长时间。

Behavior行为

Mechanics机制

Unlike db.collection.count(), db.collection.countDocuments() does not use the metadata to return the count. db.collection.count()不同,db.collection.countDocuments()不使用元数据来返回计数。Instead, it performs an aggregation of the document to return an accurate count, even after an unclean shutdown or in the presence of orphaned documents in a sharded cluster.相反,它会对文档进行聚合,以返回准确的计数,即使在不干净的关闭之后或在分片集群中存在孤立文档的情况下也是如此。

db.collection.countDocuments() wraps the following aggregation operation and returns just the value of n:包装以下聚合操作并仅返回n的值:

db.collection.aggregate([
{ $match: <query> },
{ $group: { _id: null, n: { $sum: 1 } } }
])

Empty or Non-Existing Collections and Views空的或不存在的集合和视图

Starting in version 4.2.1, db.collection.countDocuments() returns 0 on an empty or non-existing collection or view.从4.2.1版本开始,db.collection.countDocuments()在空的或不存在的集合或视图上返回0

In earlier versions of MongoDB, db.collection.countDocuments() errors on an empty or non-existing collection or view.在早期版本的MongoDB中,db.collection.countDocuments()在空的或不存在的集合或视图上出错。

Query Restrictions查询限制

You cannot use the following query operators as part of the query expression for db.collection.countDocuments():不能将以下查询运算符用作db.collection.countDocuments()的查询表达式的一部分:

Restricted Operator受限运算符Alternative可供替代的
$whereAs an alternative, use $expr instead.作为替代方案,请改用$expr
$nearAs an alternative, use $geoWithin with $center; i.e. 另一种选择是,将$geoWithin$center一起使用;即。
{ $geoWithin: { $center: [ [ <x>, <y> ], <radius> ] } }
$nearSphereAs an alternative, use $geoWithin with $centerSphere; i.e. 另一种选择是,将$geoWithin$centerSphere;即,
{ $geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] } }

Transactions事务

db.collection.countDocuments() can be used inside multi-document transactions.可以在多文档事务中使用。

When you use db.collection.countDocuments() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions.在事务中使用db.collection.countDocuments()时,生成的计数不会筛选掉任何未提交的多文档事务

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会产生更高的性能成本,并且多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入文档和数组)将继续是您的数据和用例的最佳选择。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,对数据进行适当建模将最大限度地减少对多文档事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项

Client Disconnection客户端断开连接

Starting in MongoDB 4.2, if the client that issued db.collection.countDocuments() disconnects before the operation completes, MongoDB marks db.collection.countDocuments() for termination using killOp.从MongoDB 4.2开始,如果发出db.collection.countDocuments()的客户端在操作完成前断开连接,MongoDB会使用killOp标记db.collection.countDocuments()终止。

Examples实例

Count all Documents in a Collection统计集合中的所有文档

To count the number of all documents in the orders collection, use the following operation:要计算orders集合中所有文档的数量,请使用以下操作:

db.orders.countDocuments({})

Count all Documents that Match a Query统计与查询匹配的所有文档

Count the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012'):统计orders集合中字段ord_dt大于new Date('01/01/2012')的文档数:

db.orders.countDocuments( { ord_dt: { $gt: new Date('01/01/2012') } }, { limit: 100 } )