Database Manual / Reference / Query Language / CRUD Commands

count (database command)

Definition定义

count

Counts the number of documents in a collection or a view. Returns a document that contains this count and as well as the command status.统计集合或视图中的文档数。返回一个包含此计数和命令状态的文档。

Tip

In mongosh, this command can also be run through the count() helper method.mongosh中,此命令也可以通过count()辅助方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. 助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要便利性或需要额外的返回字段,请使用database命令。

Note

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

Compatibility兼容性

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

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

Important

This command has limited support in M0 and Flex clusters. For more information, see Unsupported Commands.此命令在M0和Flex集群中的支持有限。有关详细信息,请参阅不支持的命令

  • 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语法

The command has the following syntax:该命令具有以下语法:

Note

MongoDB validates option names for the count command. The command errors if you specify an unknown option name.MongoDB验证count命令的选项名称。如果指定未知的选项名称,则命令会出错。

db.runCommand(
{
count: <collection or view>,
query: <document>,
limit: <integer>,
skip: <integer>,
hint: <hint>,
readConcern: <document>,
maxTimeMS: <integer>,
collation: <document>,
comment: <any>
}
)

Command Fields命令字段

count has the following fields:具有以下字段:

Field字段TypeDescription描述
countstringThe name of the collection or view to count.要计数的集合或视图的名称。
querydocumentOptional. A query that selects which documents to count in the collection or view.可选。选择要在集合或视图中计数的文档的查询。</td>
limitintegerOptional. The maximum number of matching documents to return.可选。要返回的匹配文档的最大数量。
skipintegerOptional. The number of matching documents to skip before returning results.可选。在返回结果之前要跳过的匹配文档的数量。
hintstring or documentOptional. The index to use. Specify either the index name as a string or the index specification document.可选。要使用的索引。将索引名称指定为字符串或索引规范文档。
readConcern

document

Optional. Specifies the read concern. The option has the following syntax:可选。指定读取关注。该选项具有以下语法:

readConcern: { level: <value> }

Possible read concern levels are:可能的读取关注级别包括:

  • "local". This is the default read concern level for read operations against the primary and secondaries.。这是针对主要和次要读取操作的默认读取关注级别。
  • "available". Available for read operations against the primary and secondaries. 。可用于对初级和次级进行读取操作。"available" behaves the same as "local" against the primary and non-sharded secondaries. The query returns the instance's most recent data.
  • "majority". Available for replica sets that use WiredTiger storage engine.
  • "linearizable". Available for read operations on the primary only.
  • "snapshot". Available for multi-document transactions and certain read operations outside of multi-document transactions.

For more formation on the read concern levels, see Read Concern Levels.

maxTimeMSnon-negative integer

Optional.

Specifies a time limit in milliseconds. If you do not specify a value for maxTimeMS, operations will not time out. A value of 0 explicitly specifies the default unbounded behavior.

MongoDB terminates operations that exceed their allotted time limit using the same mechanism as db.killOp(). MongoDB only terminates an operation at one of its designated interrupt points.

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.

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.

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.

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.

commentany

Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:

A comment can be any valid BSON type (string, integer, object, array, etc).

Stable API Support支持

Starting in MongoDB 6.0, the count command is included in Stable API V1. To use the count command in the Stable API, you must connect your driver to a deployment that is running MongoDB 6.0 or greater.从MongoDB 6.0开始,

count

命令包含在Stable API V1中。要在Stable API中使用count命令,必须将驱动程序连接到运行MongoDB 6.0或更高版本的部署。

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 commands 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.关于基于集合元数据的计数,请参阅带有计数选项的collStats管道阶段

Count and Transactions计数和事务

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

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

Accuracy and Sharded Clusters精度和分片集群

On a sharded cluster, the count command when run without a query predicate can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.在分片集群上,如果存在孤立文档或正在进行块迁移,则在没有查询谓词的情况下运行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:

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.

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.

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.

Run validate on each collection on the mongod to restore statistics after an unclean shutdown.

After an unclean shutdown:

Note

This loss of accuracy only applies to count operations that do not include a query document.

Client Disconnection

If the client that issued count disconnects before the operation completes, MongoDB marks count for termination using killOp.

Examples示例

The following sections provide examples of the count command.

Count All Documents

The following operation counts the number of all documents in the orders collection:

db.runCommand( { count: 'orders' } )

In the result, the n, which represents the count, is 26, and the command status ok is 1:

{ "n" : 26, "ok" : 1 }

Count Documents That Match a Query

The following operation returns a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012'):以下操作返回orders集合中ord_dt字段值大于Date('01/01/2012')的文档计数:

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

In the result, the n, which represents the count, is 13 and the command status ok is 1:结果,表示计数的n13,命令状态ok1

{ "n" : 13, "ok" : 1 }

Skip Documents in Count

The following operation returns a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012') and skip the first 10 matching documents:

db.runCommand( { count:'orders',
query: { ord_dt: { $gt: new Date('01/01/2012') } },
skip: 10 } )

In the result, the n, which represents the count, is 3 and the command status ok is 1:

{ "n" : 3, "ok" : 1 }

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

The following operation uses the index { status: 1 } to return a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012') and the status field is equal to "D":

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

In the result, the n, which represents the count, is 1 and the command status ok is 1:

{ "n" : 1, "ok" : 1 }

Override Default Read Concern覆盖默认读取关注

To override the default read concern level of "local", use the readConcern option.要覆盖默认的读取关注级别"local",请使用readConcern选项。

The following operation on a replica set specifies a Read Concern of "majority" to read the most recent copy of the data confirmed as having been written to a majority of the nodes.

Important

  • To use the readConcern level of "majority", you must specify a nonempty query condition.
  • Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.
db.runCommand(
{
count: "restaurants",
query: { rating: { $gte: 4 } },
readConcern: { level: "majority" }
}
)

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.