db.collection.countDocuments()

On this page本页内容

Definition定义

db.collection.countDocuments(query, options)
Important重要
mongosh Method

This is a mongosh method. 这是蒙古方法。This is not the documentation for Node.js or other programming language specific driver methods.这不是Node.js或其他特定于编程语言的驱动程序方法的文档。

In most cases, mongosh methods work the same way as the legacy mongo shell methods. 在大多数情况下,mongosh方法的工作方式与传统mongoshell方法相同。However, some legacy methods are unavailable in mongosh.然而,一些遗留方法在mongosh中不可用。

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:有关旧版mongo shell文档,请参阅相应MongoDB Server版本的文档:

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

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描述
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 (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-series)开始,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
$near

As an alternative, use $geoWithin with $center; i.e.

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

As an alternative, use $geoWithin with $centerSphere; i.e.

{ $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()标记为终止(即操作上的killOp)。

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 } )
←  db.collection.count()db.collection.createIndex() →