> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# count (database command)

## Definition

Counts documents in a collection or view. Returns a document with the count, `n`, and the command status, `ok`.

**Tip:**

In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#std-program-mongosh), this command can also be run through the [`count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count)  helper method.

Helper methods are convenient for [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#std-program-mongosh) users, but they may not return the same level of information as database commands.  In cases where the convenience is not needed or the additional return fields are required, use the database command.

**Note:**

MongoDB drivers deprecate their cursor and collection `count()` APIs and use driver-specific APIs that correspond to [`db.collection.countDocuments()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#mongodb-method-db.collection.countDocuments) and [`db.collection.estimatedDocumentCount()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#mongodb-method-db.collection.estimatedDocumentCount). For specific API names, see your driver's API documentation.

## Compatibility

This command is available in deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

**Important:**

This command has limited support in M0 and Flex clusters. For more information, see [Unsupported Commands.](https://www.mongodb.com/docs/atlas/unsupported-commands/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

The command has the following syntax:

**Note:**

MongoDB validates option names for the [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command. The command errors if you specify an unknown option name.

```javascript
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`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) has the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `count` | string | The name of the collection or view to count. |
| `query` | document | Optional. A query that selects which documents to count in the collection or view. |
| `limit` | integer | Optional. The maximum number of matching documents to return. |
| `skip` | integer | Optional. The number of matching documents to skip before returning results. |
| `hint` | string or document | Optional. The index to use. Specify either the index name as a string or the index specification document. |
| `readConcern` | document | Optional. Specifies the [read concern](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-read-concern). The option has the following syntax: `readConcern: { level: <value> }` Possible read concern levels are: [`"local"`](https://www.mongodb.com/docs/manual/reference/read-concern-local.md#mongodb-readconcern-readconcern.-local-). This is the default read concern level for read operations against the primary and secondaries.; [`"available"`](https://www.mongodb.com/docs/manual/reference/read-concern-available.md#mongodb-readconcern-readconcern.-available-). Available for read operations against the primary and secondaries. [`"available"`](https://www.mongodb.com/docs/manual/reference/read-concern-available.md#mongodb-readconcern-readconcern.-available-) behaves the same as [`"local"`](https://www.mongodb.com/docs/manual/reference/read-concern-local.md#mongodb-readconcern-readconcern.-local-) against the primary and non-sharded secondaries. The query returns the instance's most recent data.; [`"majority"`](https://www.mongodb.com/docs/manual/reference/read-concern-majority.md#mongodb-readconcern-readconcern.-majority-). Available for replica sets that use [WiredTiger storage engine.](https://www.mongodb.com/docs/manual/core/wiredtiger.md#std-label-storage-wiredtiger); [`"linearizable"`](https://www.mongodb.com/docs/manual/reference/read-concern-linearizable.md#mongodb-readconcern-readconcern.-linearizable-). Available for read operations on the [`primary`](https://www.mongodb.com/docs/manual/reference/replica-states.md#mongodb-replstate-replstate.PRIMARY) only.; [`"snapshot"`](https://www.mongodb.com/docs/manual/reference/read-concern-snapshot.md#mongodb-readconcern-readconcern.-snapshot-). Available for [multi-document transactions](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) and certain read operations outside of multi-document transactions. For more formation on the read concern levels, see [Read Concern Levels.](https://www.mongodb.com/docs/manual/reference/read-concern.md#std-label-read-concern-levels) |
| `maxTimeMS` | non-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()`](https://www.mongodb.com/docs/manual/reference/method/db.killOp.md#mongodb-method-db.killOp). MongoDB only terminates an operation at one of its designated [interrupt points.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-interrupt-point) |
| `collation` | document | Optional. Optional. Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation)  to use for the operation. [Collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-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.](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation-document-fields) If the collation is unspecified but the collection has a default collation (see [`db.createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection.md#mongodb-method-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. |
| `comment` | any | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations: [mongod log messages](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref), in the `attr.command.cursor.comment` field.; [Database profiler](https://www.mongodb.com/docs/manual/reference/database-profiler.md#std-label-profiler) output, in the [`command.comment`](https://www.mongodb.com/docs/manual/reference/database-profiler.md#mongodb-data-system.profile.command) field.; [`currentOp`](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#mongodb-dbcommand-dbcmd.currentOp) output, in the [`command.comment`](https://www.mongodb.com/docs/manual/reference/command/currentOp.md#mongodb-data-currentOp.command) field. A comment can be any valid [BSON type](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-bson-types) (string, integer, object, array, etc). |

## Stable API Support

Starting in MongoDB 6.0, the `count` command is included in [Stable API](https://www.mongodb.com/docs/manual/reference/stable-api.md#std-label-stable-api) V1. To use the `count` command in the Stable API, you must connect your driver to a deployment running MongoDB 6.0 or later.

## Behavior

### Inaccurate Counts Without Query Predicate

When you call [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) without a query predicate, you may receive inaccurate document counts. Without a query predicate, [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) commands return results based on the collection's metadata, which may result in an approximate count. In particular,

- On a sharded cluster, the resulting count does not correctly filter out [orphaned documents.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document)

- After an unclean shutdown or [file copy based initial sync](https://www.mongodb.com/docs/manual/core/replica-set-sync.md#std-label-replica-set-initial-sync-file-copy-based), the count may be incorrect.

For counts based on collection metadata, see also [collStats pipeline stage with the count](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#std-label-collstat-count) option.

### Count and Transactions

When you use [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) in a transaction, the resulting count will not filter out any uncommitted [multi-document transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions)

For details, see [Transactions and Count Operations.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-ops-count)

### Accuracy and Sharded Clusters

On a sharded cluster, the [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) command when run without a query predicate can result in an *inaccurate* count if [orphaned documents](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document) exist or if a [chunk migration](https://www.mongodb.com/docs/manual/core/sharding-balancer-administration.md#std-label-sharding-balancing) is in progress.

To avoid these situations, on a sharded cluster, use the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) method:

You can use the [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-pipeline-pipe.-count) stage to count the documents. For example, the following operation counts the documents in a collection:

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

The [`$count`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/count.md#mongodb-pipeline-pipe.-count) stage is equivalent to the following [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) + [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) sequence:

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

**See also:**

[`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#mongodb-pipeline-pipe.-collStats) to return an approximate count based on the collection's metadata.

### Accuracy after Unexpected Shutdown

After an unclean shutdown of a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) using the [Wired Tiger](https://www.mongodb.com/docs/manual/core/wiredtiger.md) storage engine, count statistics reported by [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) may be inaccurate.

The amount of drift depends on the number of insert, update, or delete operations performed between the last [checkpoint](https://www.mongodb.com/docs/manual/core/wiredtiger.md#std-label-storage-wiredtiger-checkpoints) and the unclean shutdown. Checkpoints usually occur every 60 seconds. However, [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) instances running with non-default [`--syncdelay`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--syncdelay) settings may have more or less frequent checkpoints.

Run [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) on each collection on the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) to restore statistics after an unclean shutdown.

After an unclean shutdown:

- [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) updates the [count statistic](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#std-label-collstat-count) in the [`collStats`](https://www.mongodb.com/docs/manual/reference/command/collStats.md#mongodb-dbcommand-dbcmd.collStats) [output](https://www.mongodb.com/docs/manual/reference/command/collStats.md#std-label-collStats-output) with the latest value.

- Other statistics like the number of documents inserted or removed in the [`collStats`](https://www.mongodb.com/docs/manual/reference/command/collStats.md#mongodb-dbcommand-dbcmd.collStats) [output](https://www.mongodb.com/docs/manual/reference/command/collStats.md#std-label-collStats-output) are estimates.

**Note:**

This loss of accuracy only applies to [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) operations that do *not* include a query document.

### Client Disconnection

If the client that issued [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) disconnects before the operation completes, MongoDB marks [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count) for termination using [`killOp`.](https://www.mongodb.com/docs/manual/reference/command/killOp.md#mongodb-dbcommand-dbcmd.killOp)

## Examples

### Count All Documents

The following operation counts all documents in the `orders` collection:

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

The operation returns the following document:

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

### Count Documents That Match a Query

The following operation counts documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')`:

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

The operation returns the following document:

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

### Skip Documents in Count

The following operation counts documents in the `orders` collection where the `ord_dt` field is greater than `Date('01/01/2012')`, skipping the first `10` matches:

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

The operation returns the following document:

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

### Specify the Index to Use

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

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

The operation returns the following document:

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

### Override Default Read Concern

To override the default read concern level of [`"local"`](https://www.mongodb.com/docs/manual/reference/read-concern-local.md#mongodb-readconcern-readconcern.-local-), use the `readConcern` option.

The following operation on a replica set specifies a [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern.md) of [`"majority"`](https://www.mongodb.com/docs/manual/reference/read-concern-majority.md#mongodb-readconcern-readconcern.-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](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-read-concern) level, the most recent data on a node may not reflect the most recent version of the data in the system.

```javascript
db.runCommand(
   {
     count: "restaurants",
     query: { rating: { $gte: 4 } },
     readConcern: { level: "majority" }
   }
)
```

To ensure that a single thread can read its own writes, use [`"majority"`](https://www.mongodb.com/docs/manual/reference/read-concern-majority.md#mongodb-readconcern-readconcern.-majority-) read concern and [`"majority"`](https://www.mongodb.com/docs/manual/reference/write-concern.md#mongodb-writeconcern-writeconcern.-majority-) write concern against the primary of the replica set.
