Database Manual / Reference / mongosh Methods / Cursors

cursor.count() (mongosh method方法)

Definition定义

cursor.count()

Important

mongosh Method方法

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.本页记录了一种mongosh方法。这不是针对特定语言驱动程序(如Node.js)的文档。

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档

Note

MongoDB drivers deprecate their respective cursor and collection count() APIs in favor of new APIs that corresponds to countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver API documentation.MongoDB驱动程序弃用了各自的游标和集合count()API,转而支持与countDocuments()estimatedDocumentCount()相对应的新API。有关给定驱动程序的特定API名称,请参阅驱动程序API文档。

Counts the number of documents referenced by a cursor. Append the count() method to a find() query to return the number of matching documents. 统计游标引用的文档数量。将count()方法附加到find()查询中,以返回匹配文档的数量。The operation does not perform the query but instead counts the results that would be returned by the query.该操作不执行查询,而是计算查询返回的结果。

The count() method has the following prototype form:count()方法具有以下原型形式:

db.collection.find(<query>).count()

The count() method has the following parameter:count()方法有以下参数:

Parameter参数Type类型Description描述
applySkipLimitboolean布尔值

Optional. 可选。mongosh ignores any value you set for this option. The value defaults to true.忽略为此选项设置的任何值。该值默认为true

The option specifies whether to consider the effects of the cursor.skip() and cursor.limit() methods in the count. 该选项指定是否在计数中考虑cursor.skip()cursor.limit()方法的影响。By default, the count() method ignores the effects of the cursor.skip() and cursor.limit(). You must set applySkipLimit to true to consider the effect of these methods.默认情况下,count()方法忽略cursor.skip()cursor.limit()的效果。您必须将applySkipLimit设置为true才能考虑这些方法的效果。

The legacy mongo shell, which is now deprecated, used your setting for this option.现在已弃用的旧版mongo shell使用了您对此选项的设置。

MongoDB also provides an equivalent db.collection.count() as an alternative to the db.collection.find(<query>).count() construct.MongoDB还提供了一个等效的db.collection.count()作为db.collection.find(<query>).count()构造的替代方案。

MongoDB supports the use of hint() with count(). MongoDB支持将hint()count()结合使用。See Specify the Index to Use for an example.请参见指定要使用的索引以获取示例。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Behavior行为

Inaccurate Counts Without Query Predicate没有查询谓词的计数不准确

When you call count() on a find() operation which does not specify a query predicate, the count() method can return inaccurate document counts. 当您对未指定查询谓词的find()操作调用count()时,count()方法可能会返回不准确的文档计数。These count() methods return results based on the collection's metadata, which may result in an approximate count. In particular,这些count()方法根据集合的元数据返回结果,这可能会导致近似计数。特别地,

For counts based on collection metadata, see also collStats pipeline stage with the count option.关于基于集合元数据的计数,请参阅带有count选项的collStats管道阶段

Count and Transactions计数和事务

You cannot use count and shell helpers count() and db.collection.count() in transactions.您不能在事务中使用count和shell助手count()db.collection.count()

For details, see Transactions and Count Operations.有关详细信息,请参阅事务和计数操作

Sharded Clusters分片集群

On a sharded cluster, count() without a query predicate in the find can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.在分片集群上,如果孤立文档存在或正在进行块迁移,则find中没有查询谓词的count()可能会导致计数不准确。

To avoid these situations, on a sharded cluster, use the db.collection.aggregate() method:为了避免这些情况,在分片集群上,使用db.collection.aggregate()方法:

You can use the $count stage to count the documents. For example, the following operation counts the documents in a collection:您可以使用$count阶段对文档进行计数。例如,以下操作对集合中的文档进行计数:

db.collection.aggregate( [
{ $count: "myCount" }
])

The $count stage is equivalent to the following $group + $project sequence:$count阶段相当于以下$group+$project序列:

db.collection.aggregate( [
{ $group: { _id: null, count: { $sum: 1 } } },
{ $project: { _id: 0 } }
] )

Tip

$collStats to return an approximate count based on the collection's metadata.根据集合的元数据返回近似计数。

Index Use索引使用

Consider a collection with the following index:考虑一个具有以下索引的集合:

{ a: 1, b: 1 }

When performing a count, MongoDB can return the count using only the index if:在执行计数时,MongoDB可以在以下情况下仅使用索引返回计数:

  • the query can use an index,查询可以使用索引,
  • the query only contains conditions on the keys of the index, and查询仅包含索引键的条件,以及
  • the query predicates access a single contiguous range of index keys.查询谓词访问单个连续的索引键范围。

For example, the following operations can return the count using only the index:例如,以下操作可以仅使用索引返回计数:

db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { a: 5, b: { $gt: 10 } } ).count()

If, however, the query can use an index but the query predicates do not access a single contiguous range of index keys or the query also contains conditions on fields outside the index, then in addition to using the index, MongoDB must also read the documents to return the count.但是,如果查询可以使用索引,但查询谓词不能访问单个连续的索引键范围,或者查询还包含索引外字段的条件,那么除了使用索引外,MongoDB还必须读取文档以返回计数。

db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { a: 5, b: 5, c: 5 } ).count()

In such cases, during the initial read of the documents, MongoDB pages the documents into memory such that subsequent calls of the same count operation will have better performance.在这种情况下,在文档的初始读取过程中,MongoDB会将文档分页到内存中,这样后续对相同计数操作的调用将具有更好的性能。

Examples示例

The following are examples of the count() method.以下是count()方法的示例。

Count All Documents统计所有文档

The following operation counts the number of all documents in the orders collection:以下操作统计orders集合中所有文档的数量:

db.orders.find().count()

Count Documents That Match a Query统计与查询匹配的文档

The following operation counts 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.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

Limit Documents in Count限制文档计数

The following operation counts the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012') taking into account the effect of the limit(5):以下操作计算orders集合中字段ord_dt大于new Date('01/01/2012')的文档数量,同时考虑limit(5)的影响:

db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)

Specify the Index to Use指定要使用的索引

The following operation uses the index named "status_1", which has the index key specification of { status: 1 }, to return a count of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012') and the status field is equal to "D":以下操作使用名为"status_1"的索引(索引键规范为{ status: 1 })返回orders集合中字段ord_dt大于new Date('01/01/2012')status字段等于"D"的文档计数:

db.orders.find(
{ ord_dt: { $gt: new Date('01/01/2012') }, status: "D" }
).hint( "status_1" ).count()