Database Manual / Reference / mongosh Methods / Collections

db.collection.count() (mongosh method方法)

Definition定义

db.collection.count(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.本页记录了一种mongosh方法。这不是数据库命令或特定语言驱动程序(如Node.js)的文档。

For the database command, see the count command.有关数据库命令,请参阅count命令

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 for countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver documentation.MongoDB驱动程序弃用了各自的游标和集合count()API,转而支持countDocuments()estimatedDocumentCount()的新API。有关给定驱动程序的特定API名称,请参阅驱动程序文档。

Returns the count of documents that would match a find() query for the collection or view. 返回与集合或视图的find()查询匹配的文档数。The db.collection.count() method does not perform the find() operation but instead counts and returns the number of results that match a query.db.collection.count()方法不执行find()操作,而是计数并返回与查询匹配的结果数量。

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. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关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的源代码可用、免费使用和自我管理版本

Syntax语法

This method takes the following parameters:此方法采用以下参数:

Parameter参数Type类型Description描述
querydocument文档The query selection criteria.查询选择条件。
optionsdocument文档Optional. 可选。Extra options for modifying the count.修改计数的额外选项。

The options document contains the following fields:options文档包含以下字段:

Field字段Type类型Description描述
limitinteger整数Optional. 可选。The maximum number of documents to count.要计数的最大文档数。
skipinteger整数Optional. 可选。The number of documents to skip before counting.计数前要跳过的文档数。
hintstring or document字符串或文档Optional. 可选。An index name hint or specification for the query.查询的索引名称提示或规范。
maxTimeMSinteger整数Optional. 可选。The maximum amount of time to allow the query to run.允许查询运行的最长时间。
readConcernstring字符串

Optional. 可选。Specifies the read concern. 指定读取关注The default level is "local".默认级别为"local"

To ensure that a single thread can read its own writes, use "majority" read concern and "majority" write concern against the primary of the replica set.为了确保单个线程可以读取自己的写入,请对副本集的主线程使用"majority"读取关注和"majority"写入关注。

To use a read concern level of "majority", you must specify a nonempty query condition.要使用"majority"读取关注级别,您必须指定一个非空query条件。

collationdocument文档

Optional.可选。

Specifies the collation to use for the operation.指定用于操作的排序规则

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。

The collation option has the following syntax:排序规则选项具有以下语法:

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.指定排序规则时,locale字段是必填的;所有其他排序字段都是可选的。有关字段的描述,请参阅排序规则文档

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.如果未指定排序规则,但集合具有默认排序规则(请参阅db.createCollection()),则操作将使用为集合指定的排序规则。

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中用于字符串比较的简单二进制比较。

You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.不能为操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一个排序规则,对排序使用另一个。

count() is equivalent to the db.collection.find(query).count() construct.等效于db.collection.find(query).count()构造。

Behavior行为

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

When you call count() without a query predicate, you may receive inaccurate document counts. Without a query predicate, count() methods return results based on the collection's metadata, which may result in an approximate count. In particular,当您在没有查询谓词的情况下调用 count()时,您可能会收到不准确的文档计数。如果没有查询谓词, 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, db.collection.count() without a query predicate can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.在分片集群上,如果存在孤立文档或正在进行块迁移,则没有查询谓词的db.collection.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会将文档分页到内存中,这样后续对相同计数操作的调用将具有更好的性能。

Accuracy after Unexpected Shutdown意外停机后的准确性

After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count() may be inaccurate.使用Wired Tiger存储引擎不干净地关闭mongod后,count()报告的计数统计数据可能不准确。

The amount of drift depends on the number of insert, update, or delete operations performed between the last checkpoint and the unclean shutdown. 漂移量取决于在最后一个检查点和不干净关闭之间执行的插入、更新或删除操作的数量。Checkpoints usually occur every 60 seconds. However, mongod instances running with non-default --syncdelay settings may have more or less frequent checkpoints.检查点通常每60秒出现一次。然而,使用非默认的--syncdelay设置运行的mongod实例可能或多或少地具有检查点。

Run validate on each collection on the mongod to restore statistics after an unclean shutdown.mongod上的每个集合上运行validate,以在不干净关闭后恢复统计数据。

After an unclean shutdown:不干净停机后:

Note

This loss of accuracy only applies to count() operations that do not include a query predicate.这种准确性损失仅适用于不包含查询谓词的count()操作。

Client Disconnection客户端断开连接

If the client that issued db.collection.count() disconnects before the operation completes, MongoDB marks db.collection.count() for termination using killOp.如果发出db.collection.count()的客户端在操作完成之前断开连接,MongoDB将使用killOp标记db.collection.count()以终止。

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.count()

This operation is equivalent to the following:此操作相当于以下操作:

db.orders.find().count()

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

The query is equivalent to the following:该查询等效于以下内容:

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