db.collection.countDocuments()

On this page本页内容

Definition定义

db.collection.countDocuments(query, options)

mongo Shell Method

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. 本页记录了mongo shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。

New in version 4.0.3.版本4.0.3中新增。

Returns the count of documents that match the query for a collection or view. 返回与集合或视图的查询匹配的文档数。The method wraps the $group aggregation stage with a $sum expression to perform the count and is available for use in Transactions.该方法使用$sum表达式包装$group聚合阶段以执行计数,并可在事务中使用。

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

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

Field字段Type类型Description描述
limit integer Optional.可选。The maximum number of documents to count.要计数的最大文档数。
skip integer Optional.可选。The number of documents to skip before counting.计数前要跳过的文档数。
hint string or document Optional.可选。An index name or the index specification to use for the query.用于查询的索引名称或索引规范。
maxTimeMS integer Optional.可选。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 (and 4.0-series in 4.0.13), db.collection.countDocuments() returns 0 on an empty or non-existing collection or view.从版本4.2.1(以及4.0.13中的4.0系列)开始,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可供替代的
$where As an alternative, use $expr instead.另一种选择是使用$expr
$near

As an alternative, use $geoWithin with $center; i.e.或者,使用$geoWithin配合$center;比如。

{ $geoWithin: { $center: [ [ <x>, <y> ], <radius> ] } }
$nearSphere

As 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.可以在多文档事务中使用。

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.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项

Client Disconnection客户端断开

Starting in MongoDB 4.2, if the client that issued the db.collection.countDocuments() disconnects before the operation completes, MongoDB marks the db.collection.countDocuments() for termination (i.e. killOp on the operation).从MongoDB 4.2开始,如果发出db.collection.countDocuments()的客户端在操作完成之前断开连接,MongoDB会将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 } )