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

# validate (database command)

## Definition

**Changed in version 6.2**

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command checks a collection's data and indexes for correctness and returns the results. The command also repairs any inconsistencies in the count and data size of a collection.

**Tip:**

In [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#std-program-mongosh), this command can also be run through the [`validate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.validate.md#mongodb-method-db.collection.validate) 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.

**Changed in version 5.0**

Starting in version 5.0, the [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command can also find inconsistencies in the collection and fix them if possible.

Index inconsistencies include:

- An index is [multikey](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-index-type-multikey) but there are no multikey fields.

- An index has [multikeyPaths](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-compound_multikey_indexes) covering fields that are not multikey.

- An index does not have [multikeyPaths](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-compound_multikey_indexes) but there are multikey documents (for indexes built before 3.4).

If any inconsistencies are detected by the [`db.collection.validate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.validate.md#mongodb-method-db.collection.validate) command, a warning is returned and the repair flag on the index is set to `true`.

[`db.collection.validate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.validate.md#mongodb-method-db.collection.validate) also validates any documents that violate the collection's [schema validation rules.](https://www.mongodb.com/docs/manual/core/schema-validation.md#std-label-schema-validation-document)

**Note:**

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command does not support [views](https://www.mongodb.com/docs/manual/core/views.md) and raises an error when run against a view.

The [`db.collection.validate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.validate.md#mongodb-method-db.collection.validate) method in [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) provides a wrapper around [`validate`.](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate)

## 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 is not supported 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:

```javascript
db.runCommand(
   {
     validate: <string>,  // Collection name
     full: <boolean>,  // Optional
     repair: <boolean>,  // Optional, added in MongoDB 5.0
     metadata: <boolean>,  // Optional, added in MongoDB 5.0.4
     checkBSONConformance: <boolean>  // Optional, added in MongoDB 6.2
     background: <boolean> // Optional
   }
)
```

## Command Fields

The command takes the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `validate` | string | The name of the collection to validate. |
| `full` | boolean | Optional. A flag that determines whether the command performs a slower but more thorough check or a faster but less thorough check. If `true`, performs a more thorough check with the following exception:Full validation on the `oplog` for WiredTiger skips the more thorough check. The [`validate.warnings`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.warnings) includes a notice of the behavior.; If `false`, omits some checks for a faster but less thorough check. The default is `false`. For the WiredTiger storage engine, only the `full` validation process will force a checkpoint and flush all in-memory data to disk before verifying the on-disk data. |
| `repair` | boolean | *Optional*. A flag that determines whether the command performs a repair. If `true`, a repair is performed.; If `false`, no repair is performed. The default is `false`. A repair can only be run on a standalone node. The repair fixes the following issues: If missing index entries are found, the missing keys are inserted into the index.; If extra index entries are found, the extra keys are removed from the index.; If corrupt documents with invalid BSON data are found, the documents are removed. IMPORTANT: To set `repair` to `true`, you must set the `fixMultikey` option to `true`. For more information, see the [`--repair`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#std-option-mongod.--repair) option for [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) **New in version 5.0** |
| `metadata` | boolean | *Optional*. A flag which allows users to perform a quick validation to detect invalid index options without scanning all of the documents and indexes. If `true`, a metadata validation scan is performed.; If `false`, no metadata validation scan is not performed. The default is `false`. Running the validate command with `{ metadata: true }` is not supported with any other [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) options. The `metadata` validation option: Provides you a faster way of identifying invalid indexes by scanning only collections metadata.; Provides an alternative to dropping and recreating multiple invalid indexes when used with the [`collMod`](https://www.mongodb.com/docs/manual/reference/command/collmod.md#mongodb-dbcommand-dbcmd.collMod) command. The `metadata` validation option only scans collection metadata to find invalid indexes more quickly. If there is an invalid index detected, the validate command will prompt you to use the [`collMod`](https://www.mongodb.com/docs/manual/reference/command/collmod.md#mongodb-dbcommand-dbcmd.collMod) command to remove invalid indexes. `db.runCommand( { collMod: <collectionName> } )` **New in version 5.0.4** |
| `checkBSONConformance` | boolean | *Optional*. If `true`, the collection is checked to ensure the [BSON documents](https://www.mongodb.com/docs/manual/core/document.md#std-label-bson-document-format) conform to the BSON specifications. The checks increase the time to complete the validation operation. Any issues are returned as a warning. `checkBSONConformance`: Default is `false`.; Cannot be used with:`repair` set to `true`.; `metadata` set to `true`. **New in version 6.2** |
| `fixMultikey` | boolean | *Optional*. If `true`, MongoDB fixes the following issues: If the `validate` command finds [multikey](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-index-type-multikey) documents for a non-multikey index, MongoDB changes the index to a multikey index.; If the `validate` command finds [multikey](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey.md#std-label-index-type-multikey) documents that aren't specified by an index's multikey paths, MongoDB updates index's multikey paths. The default is `false`. **New in version 8.1** |

## Behavior

### Performance

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command can be slow, particularly on larger data sets.

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command obtains an exclusive lock `W` on the collection. This will block all reads and writes on the collection until the operation finishes. When run on a secondary, the [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) operation can block all other operations on that secondary until it finishes.

**Warning:**

Due to the performance impact of validation, consider running [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) only on [secondary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-secondary) replica set nodes. You can use [`rs.stepDown()`](https://www.mongodb.com/docs/manual/reference/method/rs.stepdown.md#mongodb-method-rs.stepDown) to instruct the current [primary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-primary) node to become a secondary to avoid impacting a live primary node.

### Data Throughput Metrics

The [`$currentOp`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-pipeline-pipe.-currentOp) and the [`currentOp`](https://www.mongodb.com/docs/manual/reference/command/currentop.md#mongodb-dbcommand-dbcmd.currentOp) command include [`dataThroughputAverage`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-data--currentOp.dataThroughputAverage) and [`dataThroughputLastSecond`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/currentop.md#mongodb-data--currentOp.dataThroughputLastSecond) information for validate operations in progress.

The log messages for validate operations include `dataThroughputAverage` and `dataThroughputLastSecond` information.

### Collection Validation Improvements

Starting in MongoDB 6.2, the [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command and [`db.collection.validate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.validate.md#mongodb-method-db.collection.validate) method:

- Check collections to ensure the [BSON documents](https://www.mongodb.com/docs/manual/core/document.md#std-label-bson-document-format) conform to the BSON specifications.

- Check [time series collections](https://www.mongodb.com/docs/manual/core/timeseries-collections.md#std-label-manual-timeseries-collection) for internal data inconsistencies.

- Have a new option `checkBSONConformance` that enables comprehensive BSON checks.

Starting in MongoDB 8.3, the `validate` command and `db.collection.validate()` method check collections to ensure a collection doesn't have any documents that exceed 16 MB.

### Restrictions

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command no longer supports [afterClusterTime](https://www.mongodb.com/docs/manual/reference/read-concern.md#std-label-afterClusterTime). As such, [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) cannot be associated with [causally consistent sessions.](https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency.md#std-label-causal-consistency)

Time series collections were introduced in MongoDB 5.0. Starting in v5.2, the default internal format for storing time series measurements changed. Due to this change:

- Time series collections created before v5.2 might contain documents in both the old and new format. Internally, such collections are flagged as `timeseriesBucketsMayHaveMixedSchemaData: true`.

- Time series collections created in v5.2 or later will always contain documents in the new format. Internally, such collections are flagged as `timeseriesBucketsMayHaveMixedSchemaData: false` or not flagged at all.

When the flag is `true`, time series queries take both the new and the old format into account. When the flag is `false` or missing, time series queries take only the new format into account.

Due to a bug described in [SERVER-91194](https://jira.mongodb.org/browse/SERVER-91194), under some conditions the flag might be lost. When this happens for time series collections created before v5.2, read query results may be incomplete. That is, some documents may be missed, even though they are still stored on the disk.

To determine if you are impacted by this, run [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) on your time series collection. The command returns an error if the collection is affected by the bug. Your read query results may be incorrect if this is the case.

If affected, upgrade to a fixed version and set `timeseriesBucketsMayHaveMixedSchemaData` to `true` for each affected collection to ensure that future queries on the collection return correct results. The full steps for this process are located [here](https://github.com/mongodb/support-tools/tree/master/timeseries-mixed-schema).

### Index Key Format

Starting in MongoDB 6.0, the `validate` command returns a message if a [unique index](https://www.mongodb.com/docs/manual/core/index-unique.md#std-label-index-type-unique) has a key format that is incompatible. The message indicates an old format is used.

### Count and Data Size Statistics

The [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) command updates the collection's count and data size statistics 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 their correct values.

**Note:**

In the event of an [unclean shutdown](https://www.mongodb.com/docs/manual/reference/method/db.collection.estimateddocumentcount.md#std-label-estimated-document-count-unclean-shutdown), the count and data size statistics might be inaccurate.

## Examples

- To validate a collection `myCollection` using the default validation setting (specifically, [full: false](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-full)):

  ```javascript
  db.runCommand( { validate: "myCollection" } )
  ```

- To perform a full validation of collection `myCollection`, specify [full: true:](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-full)

  ```javascript
  db.runCommand( { validate: "myCollection", full: true } )
  ```

- To repair collection `myCollection`, specify [repair: true:](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-repair)

  ```javascript
  db.runCommand( { validate: "myCollection", repair: true } )
  ```

- To validate the metadata in the `myCollection` collection, specify [metadata: true:](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-metadata)

  ```javascript
  db.runCommand( { validate: "myCollection", metadata: true } )
  ```

- To perform additional BSON conformance checks in `myCollection`, specify [checkBSONConformance: true:](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-checkBSONConformance)

  ```javascript
  db.runCommand( { validate: "myCollection", checkBSONConformance: true } )
  ```

## Validate Output

**Note:**

The output may vary depending on the version and specific configuration of your MongoDB instance.

Specify [full: true](https://www.mongodb.com/docs/manual/reference/command/validate.md#std-label-cmd-validate-full) for more detailed output.

The universally unique identifier (UUID) for the collection.

**New in version 6.2**

The number of invalid documents in the collection. Invalid documents are those that are not readable, which means the [BSON](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-BSON) document is corrupt and has an error or a size mismatch.

The number of documents not conforming to the collection's schema. Non-compliant documents are not counted as invalid in [`nInvalidDocuments`.](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.nInvalidDocuments)

Starting in MongoDB 6.2, `nNonCompliantDocuments` also includes the number of documents that do not conform to the [BSON](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-BSON) or [time series collection](https://www.mongodb.com/docs/manual/core/timeseries-collections.md#std-label-manual-timeseries-collection) requirements.

The number of [documents](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-document) in the collection.

The number of indexes on the collection that were validated.

A document that contains the name and index entry count for each index on the collection.

```javascript
"keysPerIndex" : {
   "_id_" : <num>,
   "<index2_name>" : <num>,
   ...
}
```

[`keysPerIndex`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.keysPerIndex) identifies the index by its name only.

**Changed in version 8.1**

A document that contains the status of the index validation for each index and the index specification.

```javascript
"indexDetails" : {
   "_id_" : {
      "valid" : <boolean>,
      "spec" : <document>
   },
   "<index2_name>" : {
      "valid" : <boolean>,
      "spec" : <document>
   },
   ...
}
```

- [`indexDetails`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.indexDetails) identifies the specific index (or indexes) that is invalid. Earlier versions of MongoDB would mark all indexes as invalid, if any of the indexes were invalid.

- [`indexDetails`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.indexDetails) identifies the index by its name only. Earlier versions of MongoDB displayed the full namespace of the index; i.e. `<db>.<collection>.$<index_name>`.

- The `spec` document is the index specification, which varies depending on how the index is defined. Some example `spec` document fields include:

  - `spec.v`. The index version.

  - `spec.unique`. A Boolean value that indicates if the index is unique.

  - `spec.key`. The index key identifier.

  - `spec.name`. The index name.

  **New in version 8.1**

The full namespace name of the collection. Namespaces include the database name and the collection name in the form `database.collection`.

A boolean that is `true` if [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) determines that all aspects of the collection are valid. When `false`, see the [`errors`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.errors) field for more information.

A boolean that is `true` if [`validate`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-dbcommand-dbcmd.validate) repaired the collection.

**New in version 8.2**

A string that indicates what types of data inconsistencies the `validate` command attempted to repair, if detected. Possible `repairMode` values include:

- `None`: No repair actions are taken.

- `FixErrors`: Attempts to fix any validation errors.

- `AdjustMultikey`: Attempts to fix multikey inconsistencies by adjusting multikey metadata.

An array that contains warning messages, if any, regarding the validate operation itself. The warning messages do not indicate that the collection is itself invalid. For example:

```javascript
"warnings" : [
   "Could not complete validation of table:collection-28-6471619540207520785. This is a transient issue as the collection was actively in use by other operations."
],
```

If the collection is not valid (i.e [`valid`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.valid) is false), this field contains an array of messages describing the validation errors.

**Changed in version 9.0**

For index key-extraction failures on [2dsphere](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2dsphere.md#std-label-2dsphere-index) indexes, each entry is a bounded, self-contained message that identifies the affected index and path, for example:

```javascript
"errors": [
      "Could not build key for index <index> at path <path>: <error-code-name>; see log 12565600 for the failing document"
]
```

Full per-document detail is written to the [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) log under the log message with id `12565600`.

An array that contains information for each index entry that points to a document that does not exist in the collection.

```javascript
"extraIndexEntries" : [
   {
      "indexName" : <string>,
      "recordId" : <NumberLong>,  // for the non-existent document
      "indexKey" : {
         "<key1>" : <value>,
         ...
      }
   }
   ...
]
```

**Note:**

For the [`extraIndexEntries`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.extraIndexEntries) array, the sum of all the `indexKey` field sizes has a limit of 1MB where the sizes include both the keys and values for the `indexKey`. If the sum exceeds this size, the warning field displays a message.

An array that contains information for each document that is missing the corresponding index entry.

```javascript
"missingIndexEntries" : [
   {
      "indexName" : <string>,
      "recordId" : <NumberLong>,
      "idKey" : <_id key value>,     // The _id value of the document. Only present if an ``_id`` index exists.
      "indexKey" : {                 // The missing index entry
         "<key1>" : <value>,
         ...
      }
   }
   ...
 ]
```

**Note:**

For the [`missingIndexEntries`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.missingIndexEntries) array, the sum of the `idKey` field size and all its `indexKey` field sizes has a limit of 1MB where the field sizes include both the keys and values for the `idKey` and `indexKey`. If the sum exceeds this size, the warning field displays a message.

An array of `RecordId` values for documents that are unreadable, possibly because the data is damaged. These documents are reported as corrupt during validation. A `RecordId` is a 64-bit integer internal key that uniquely identifies a document in a collection.

```javascript
"corruptRecords" : [
   Long(1),  // RecordId 1
   Long(2)   // RecordId 2
]
```

**New in version 5.0**

An integer with the value `1` when the command succeeds. If the command fails the [`ok`](https://www.mongodb.com/docs/manual/reference/command/validate.md#mongodb-data-validate.ok) field has a value of `0`.

A string with the type of metadata collection used to report the size and count of collections. Possible `fastCountType` values include:

- `legacySizeStorer`

- `replicated`

- `both`

- `neither`
