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

# db.collection.countDocuments() (mongosh method)

## Definition

Returns an integer for the number of documents that match the query of the collection or view.  This method is available for use in [Transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions)

## Compatibility

This method 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

**Note:**

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, 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 `countDocuments()` method has the following form:

```javascript
db.collection.countDocuments( <query>, <options> )
```

### Parameters

The `countDocuments()` method takes the following parameters:

| Parameter | Type | Description |
| --- | --- | --- |
| query | document | The query selection criteria. To count all documents, specify an empty document. See also [Query Restrictions.](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments.md#std-label-countDocuments-restrictions) |
| options | document | Optional. Extra options that affects the count behavior. |

The `options` document can contain the following:

| Field | Type | Description |
| --- | --- | --- |
| `limit` | integer | Optional. The maximum number of documents to count. |
| `skip` | integer | Optional. The number of documents to skip before counting. |
| `hint` | string or document | Optional. An index name or the index specification to use for the query. |
| `maxTimeMS` | integer | Optional. The maximum amount of time to allow the count to run. |

## Behavior

### Mechanics

Unlike [`db.collection.count()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.count.md#mongodb-method-db.collection.count), `countDocuments()` does not use the metadata to return the count. 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](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-orphaned-document) in a sharded cluster.

`countDocuments()` wraps the following aggregation operation and returns just the value of `n`:

```javascript
db.collection.aggregate([
   { $match: <query> },
   { $group: { _id: null, n: { $sum: 1 } } }
])
```

### Empty or Non-Existing Collections and Views

`countDocuments()` returns `0` on an empty or non-existing collection or view.

### Query Restrictions

You cannot use the following query operators as part of the query expression for `countDocuments()`:

| Restricted Operator | Alternative |
| --- | --- |
| [`$where`](https://www.mongodb.com/docs/manual/reference/operator/query/where.md#mongodb-query-op.-where) | As an alternative, use [`$expr`](https://www.mongodb.com/docs/manual/reference/operator/query/expr.md#mongodb-query-op.-expr) instead. |
| [`$near`](https://www.mongodb.com/docs/manual/reference/operator/query/near.md#mongodb-query-op.-near) | As an alternative, use [`$geoWithin`](https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin.md#mongodb-query-op.-geoWithin) with [`$center`](https://www.mongodb.com/docs/manual/reference/operator/query/center.md#mongodb-query-op.-center); i.e. `{ $geoWithin: { $center: [ [ <x>, <y> ], <radius> ] } }` |
| [`$nearSphere`](https://www.mongodb.com/docs/manual/reference/operator/query/nearSphere.md#mongodb-query-op.-nearSphere) | As an alternative, use [`$geoWithin`](https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin.md#mongodb-query-op.-geoWithin) with [`$centerSphere`](https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere.md#mongodb-query-op.-centerSphere); i.e. `{ $geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] } }` |

### Transactions

`countDocuments()` can be used inside [distributed transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions)

When you use `countDocuments()` 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)

**Important:**

In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, the [denormalized data model (embedded documents and arrays)](https://www.mongodb.com/docs/manual/data-modeling/embedding.md#std-label-data-modeling-embedding) 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 distributed transactions.

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also [Production Considerations.](https://www.mongodb.com/docs/manual/core/transactions-production-consideration.md#std-label-production-considerations)

### Client Disconnection

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

## Examples

The examples on this page use data from the [sample\_mflix sample dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the sample dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

### Count all Documents in a Collection

To count the number of documents in the `movies` collection, use the following operation:

```javascript
db.movies.countDocuments( { }, { hint: "_id_"} )

```

**Note:**

If you use `db.collection.countDocuments()` with an empty query filter, MongoDB performs a full collection scan which can be inefficient. To improve performance, this example specifies a [`hint()`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-method-cursor.hint) to use the automatically generated `_id` index. Alternatively, you can use a query filter that finds all documents such as `{ "_id": { $gte: MinKey } }` to count all documents using an index.

### Count all Documents that Match a Query

This example counts the number of documents in the `movies` collection where the `directors` field contains `"David Lynch"`:

```javascript
db.movies.countDocuments( { directors: "David Lynch" } )

```

## Learn More

- [`db.collection.estimatedDocumentCount()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount.md#mongodb-method-db.collection.estimatedDocumentCount)

- [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) and [`$sum`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sum.md#mongodb-group-grp.-sum)

- [`count`](https://www.mongodb.com/docs/manual/reference/command/count.md#mongodb-dbcommand-dbcmd.count)

- [collStats pipeline stage with the count option](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats.md#std-label-collstat-count)
