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

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

## Definition

Creates indexes on collections.

## 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 [`createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) method has the following form:

```javascript
db.collection.createIndex( <keys>, <options>, <commitQuorum> )
```

### Parameters

The [`createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) method takes the following parameters:

| Parameter | Type | Description |
| --- | --- | --- |
| `keys` | document | A document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of `1`. For descending index, specify a value of `-1`. An asterisk (`*`) is not a valid index name. MongoDB supports several different index types, including: [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-feature-text); [geospatial](https://www.mongodb.com/docs/manual/geospatial-queries.md#std-label-index-feature-geospatial); [hashed indexes](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#std-label-index-type-hashed) See [index types](https://www.mongodb.com/docs/manual/core/indexes/index-types.md#std-label-index-types) for more information. [Wildcard indexes](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core) support workloads where users query against custom fields or a large variety of fields in a collection. You can create a wildcard index on a specific field and its subpaths or on all of the fields in a document.For details, see [Wildcard Indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core) |
| `options` | document | Optional. A document that contains a set of options that controls the creation of the index. See [Options](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-ensureIndex-options) for details. |
| [commitQuorum](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-createIndex-method-commitQuorum) | integer or string | Optional. The minimum number of data-bearing voting replica set members (i.e. commit quorum), including the primary, that must report a successful [index build](https://www.mongodb.com/docs/manual/core/index-creation.md#std-label-index-operations-replicated-build) before the primary marks the `indexes` as ready. A "voting" member is any replica set member where [`members[n].votes`](https://www.mongodb.com/docs/manual/reference/replica-configuration.md#mongodb-rsconf-rsconf.members-n-.votes) is greater than `0`. Supports the following values: `"votingMembers"` - all data-bearing voting replica set members (*Default*).; `"majority"` - a simple majority of data-bearing voting replica set members.; `<int>` - a specific number of data-bearing voting replica set members.; A replica set [tag name.](https://www.mongodb.com/docs/manual/tutorial/configure-replica-set-tag-sets.md) |

## Options

The `options` document contains a set of options that controls the creation of the index. Different index types can have additional options specific for that type.

Multiple index options can be specified in the same document. However, if you specify multiple option documents the [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) operation fails.

Consider the following [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) operation:

```javascript
db.collection.createIndex(
    {
        "a": 1
    },
    {
        unique: true,
        sparse: true,
        expireAfterSeconds: 3600
    }
)
```

If the options specification had been split into multiple documents like this: `{ unique: true }, { sparse: true, expireAfterSeconds: 3600 }` the index creation operation would have failed.

### Options for All Index Types

The following options are available for all index types unless otherwise specified:

| Parameter | Type | Description |
| --- | --- | --- |
| `unique` | boolean | Optional. Creates a unique index so that the collection will not accept insertion or update of documents where the index key value matches an existing value in the index. Specify `true` to create a unique index. The default value is `false`. The option is *unavailable* for [hashed indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#std-label-index-hashed-index) |
| `name` | string | Optional. The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. |
| `partialFilterExpression` | document | Optional. If specified, the index only references documents that match the filter expression. See [Partial Indexes](https://www.mongodb.com/docs/manual/core/index-partial.md) for more information. A filter expression can include: equality expressions (i.e. `field: value` or using the [`$eq`](https://www.mongodb.com/docs/manual/reference/operator/query/eq.md#mongodb-query-op.-eq) operator); [`$exists: true`](https://www.mongodb.com/docs/manual/reference/operator/query/exists.md#mongodb-query-op.-exists) expression; [`$gt`](https://www.mongodb.com/docs/manual/reference/operator/query/gt.md#mongodb-query-op.-gt), [`$gte`](https://www.mongodb.com/docs/manual/reference/operator/query/gte.md#mongodb-query-op.-gte), [`$lt`](https://www.mongodb.com/docs/manual/reference/operator/query/lt.md#mongodb-query-op.-lt), [`$lte`](https://www.mongodb.com/docs/manual/reference/operator/query/lte.md#mongodb-query-op.-lte) expressions; [`$type`](https://www.mongodb.com/docs/manual/reference/operator/query/type.md#mongodb-query-op.-type) expressions; [`$and`](https://www.mongodb.com/docs/manual/reference/operator/query/and.md#mongodb-query-op.-and) operator; [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) operator; [`$in`](https://www.mongodb.com/docs/manual/reference/operator/query/in.md#mongodb-query-op.-in) operator; [`$geoWithin`](https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin.md#mongodb-query-op.-geoWithin) operator; [`$geoIntersects`](https://www.mongodb.com/docs/manual/reference/operator/query/geoIntersects.md#mongodb-query-op.-geoIntersects) operator You can specify a `partialFilterExpression` option for all MongoDB [index types.](https://www.mongodb.com/docs/manual/core/indexes/index-types.md#std-label-index-types) |
| `sparse` | boolean | Optional. If `true`, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is `false`. See [Sparse Indexes](https://www.mongodb.com/docs/manual/core/index-sparse.md) for more information. The following index types are sparse by default and ignore this option: [2dsphere](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2dsphere.md#std-label-2dsphere-index); [2d](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2d.md#std-label-2d-index); [Text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) For a compound index that includes `2dsphere` index keys and keys for other types, only the `2dsphere` index fields determine whether the index references a document. [Partial indexes](https://www.mongodb.com/docs/manual/core/index-partial.md#std-label-index-type-partial) have a superset of the sparse index functionality. Unless your application has a specific requirement, use partial indexes instead of sparse indexes. |
| `expireAfterSeconds` | integer | Optional. Specifies a value, in seconds, as a time to live ([TTL](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-TTL)) to control how long MongoDB retains documents in this collection. This option only applies to [TTL](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-TTL) indexes. See [Expire Data from Collections by Setting TTL](https://www.mongodb.com/docs/manual/tutorial/expire-data.md#std-label-ttl-collections) for more information. If you use TTL indexes created before MongoDB 5.0, or if you want to sync data created in MongDB 5.0 with a pre-5.0 installation, see [Indexes Configured Using NaN](https://www.mongodb.com/docs/manual/tutorial/expire-data.md#std-label-expireData-warning) to avoid misconfiguration issues. The TTL index `expireAfterSeconds` value must be within `0` and `2147483647` inclusive. |
| [hidden](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-method-createIndex-hidden) | boolean | Optional. A flag that determines whether the index is [hidden](https://www.mongodb.com/docs/manual/core/index-hidden.md#std-label-index-type-hidden) from the query planner. A hidden index is not evaluated as part of the query plan selection. Default is `false`. |
| `storageEngine` | document | Optional. Allows users to configure the storage engine on a per-index basis when creating an index. The `storageEngine` option should take the following form: `storageEngine: { <storage-engine-name>: <options> }` Storage engine configuration options specified when creating indexes are validated and logged to the [oplog](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-oplog) during replication to support replica sets with members that use different storage engines. |

### Options for Collation

| Parameter | Type | Description |
| --- | --- | --- |
| `collation` | document | Optional. Specifies the [collation](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation) for the index. [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. If you have specified a collation at the collection level, then: If you do not specify a collation when creating the index, MongoDB creates the index with the collection's default collation.; If you do specify a collation when creating the index, MongoDB creates the index with the specified collation. 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) |

The following indexes only support simple binary comparison and do not support [collation:](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation)

- [Text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) indexes

- [2d](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2d.md#std-label-2d-index) indexes

**Tip:**

To create a `text` or `2d` index on a collection that has a non-simple collation, you must explicitly specify `{collation: {locale: "simple"} }` when creating the index.

#### Collation and Index Use

If you have specified a collation at the collection level, then:

- If you do not specify a collation when creating the index, MongoDB creates the index with the collection's default collation.

- If you do specify a collation when creating the index, MongoDB creates the index with the specified collation.

**Tip:**

By specifying a collation `strength` of `1` or `2`, you can create a case-insensitive index. Index with a collation `strength` of `1` is both diacritic- and case-insensitive.

You can create multiple indexes on the same key(s) with different collations. To create indexes with the same key pattern but different collations, you must supply unique index names.

To use an index for string comparisons, an operation must also specify the same collation. If an operation specifies a different collation than the index specifies, the index cannot support string comparisons on the indexed fields.

**Warning:**

Collation-aware index keys might be larger than index keys for indexes without collation because indexes that are configured with collation use ICU collation keys to achieve sort order.

### Options for `text` Indexes

The following options are available for [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) indexes only:

| Parameter | Type | Description |
| --- | --- | --- |
| `weights` | document | Optional. For [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) indexes, a document that contains field and weight pairs. The weight is an integer ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score. You can specify weights for some or all the indexed fields. See [Assign Weights to $text Query Results on Self-Managed Deployments](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text/control-text-search-results.md#std-label-control-text-search-results) to adjust the scores. The default value is `1`. Starting in MongoDB 5.0, the [weights](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text/control-text-search-results.md#std-label-specify-weights) option is only allowed for text indexes. |
| `default_language` | string | Optional. For [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) indexes, the language that determines the list of stop words and the rules for the stemmer and tokenizer. See [$text Query Languages on Self-Managed Deployments](https://www.mongodb.com/docs/manual/reference/text-search-languages.md#std-label-text-search-languages) for the available languages and [Specify Language for Text Indexes on Self-Managed MongoDB](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text/specify-text-index-language.md) for more information and examples. The default value is `english`. |
| `language_override` | string | Optional. For [text](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) indexes, the name of the field, in the collection's documents, that contains the override language for the document. The default value is `language`. See [Specify Language for Text Indexes on Self-Managed MongoDB](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text/specify-text-index-language.md#std-label-specify-language-field-text-index-example) for an example. |
| `textIndexVersion` | integer | Optional. The `text` index version number. Users can use this option to override the default version number. For available versions, see [Text Index Versions on Self-Managed Deployments.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text/text-index-versions.md#std-label-text-index-versions) |

### Options for `2dsphere` Indexes

The following option is available for [2dsphere](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2dsphere.md#std-label-2dsphere-index) indexes only:

| Parameter | Type | Description |
| --- | --- | --- |
| `2dsphereIndexVersion` | integer | Optional. The `2dsphere` index version number. Users can use this option to override the default version number. For the available versions, see [2dsphere Indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2dsphere.md#std-label-2dsphere-v2) |

### Options for `2d` Indexes

The following options are available for [2d](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2d.md#std-label-2d-index) indexes only:

| Parameter | Type | Description |
| --- | --- | --- |
| `bits` | integer | Optional. For [2d](https://www.mongodb.com/docs/manual/core/indexes/index-types/geospatial/2d.md#std-label-2d-index) indexes, the number of precision of the stored [geohash](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-geohash) value of the location data. The `bits` value ranges from 1 to 32 inclusive. The default value is `26`. |
| `min` | number | Optional. For `2d` indexes, the lower inclusive boundary for the longitude and latitude values. The default value is `-180.0`. |
| `max` | number | Optional. For `2d` indexes, the upper inclusive boundary for the longitude and latitude values. The default value is `180.0`. |

### Options for `wildcard` indexes

[Wildcard indexes](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core) can use the `wildcardProjection` option.

| Parameter | Type | Description |
| --- | --- | --- |
| `wildcardProjection` | document | Optional. Allows users to include or exclude specific field paths from a [wildcard index.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core) This option is only valid when you create a [wildcard index](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core) on all document fields. You cannot specify the `wildcardProjection` option when you create a wildcard index on a specific field path and its subfields. `wildcardProjection` works with specifications like: `{ "$**": 1 }
 
{ "userID":, "$**": 1 }  ` However, you can't define an index that includes the same field in the wildcard fields and the regular (non-wildcard) fields. To define the index correctly, use a `wildcardProjection` to exclude duplicated fields from the wildcard pattern. `wildcardProjection` does not work with a specification like: `{ "path.to.field.$**": 1 }` The `wildcardProjection` option takes the following form: `wildcardProjection: {
    "path.to.field.a": <value>,
    "path.to.field.b": <value>
}` The `<value>` can be either of the following: `1` or `true` to include the field in the wildcard index.; `0` or `false` to exclude the field from the wildcard index. |

To learn more, see:

- [About Wildcard Indexes](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard.md#std-label-wildcard-index-core)

- [Wildcard Index Restrictions](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions.md#std-label-wildcard-index-restrictions)

## Behaviors

### Recreating an Existing Index

If you call [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) for an index that already exists, MongoDB does not recreate the index.

### Index Options

#### Non-Collation and Non-Hidden Options

With the exception of the [collation option](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-method-createIndex-collation-option), if you create an index with one set of index options and then try to recreate the same index but with different index options, MongoDB will not change the options nor recreate the index.

The [hidden](https://www.mongodb.com/docs/manual/reference/command/createIndexes.md#std-label-createIndexes-hidden-option) option can be changed without dropping and recreating the index. See [Hidden Option.](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-method-createIndex-hidden-option)

To change the other index options, drop the existing index with [`db.collection.dropIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.dropIndex.md#mongodb-method-db.collection.dropIndex) before running [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) with the new options.

#### Collation Option

You can create multiple indexes on the same key(s) with different collations. To create indexes with the same key pattern but different collations, you must supply unique index names.

#### Hidden Option

To hide or unhide existing indexes, you can use the following [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) methods:

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

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

For example,

- To change the `hidden` option for an index to `true`, use the [`db.collection.hideIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.hideIndex.md#mongodb-method-db.collection.hideIndex) method:

  ```javascript
  db.movies.hideIndex( { title: 1 } )

  ```

- To change the `hidden` option for an index to `false`, use the [`db.collection.unhideIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.unhideIndex.md#mongodb-method-db.collection.unhideIndex) method:

  ```javascript
  db.movies.unhideIndex( { title: 1 } )

  ```

**See also:**

[Hidden Indexes](https://www.mongodb.com/docs/manual/core/index-hidden.md)

### Transactions

You can create collections and indexes inside a [distributed transaction](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-create-collections-indexes) if the transaction is not a cross-shard write transaction.

To use [`db.collection.createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) in a transaction, the transaction must use read concern [`"local"`](https://www.mongodb.com/docs/manual/reference/read-concern-local.md#mongodb-readconcern-readconcern.-local-). If you specify a read concern level other than [`"local"`](https://www.mongodb.com/docs/manual/reference/read-concern-local.md#mongodb-readconcern-readconcern.-local-), the transaction fails.

**See also:**

[Create Collections and Indexes in a Transaction](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions-create-collections-indexes)

### Index Builds

**Changed in version 7.1**

Starting in MongoDB 7.1, index builds are improved with faster error reporting and increased failure resilience. You can also set the minimum available disk space required for index builds using the new [`indexBuildMinAvailableDiskSpaceMB`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.indexBuildMinAvailableDiskSpaceMB) parameter, which stops index builds if disk space is too low.

The following table compares the index build behavior starting in MongoDB 7.1 with earlier versions.

| Behavior Starting in MongoDB 7.1 | Behavior in Earlier MongoDB Versions |
| --- | --- |
| Index errors found during the collection scan phase, except duplicate key errors, are returned immediately and then the index build stops. Earlier MongoDB versions return errors in the commit phase, which occurs near the end of the index build. MongoDB 7.1 helps you to rapidly diagnose index errors. For example, if an incompatible index value format is found, the error is returned to you immediately. | Index build errors can take a long time to be returned compared to MongoDB 7.1 because the errors are returned near the end of the index build in the commit phase. |
| Increased resilience for your deployment. If an index build error occurs, a [secondary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-secondary) member can request that the [primary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-primary) member stop an index build and the secondary member does not crash. A request to stop an index build is not always possible: if a member has already voted to commit the index, then the secondary cannot request that the index build stop and the secondary crashes (similar to MongoDB 7.0 and earlier). | An index build error can cause a secondary member to crash. |
| Improved disk space management for index builds. An index build may be automatically stopped if the available disk space is below the minimum specified in the [`indexBuildMinAvailableDiskSpaceMB`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.indexBuildMinAvailableDiskSpaceMB) parameter. If a member has already voted to commit the index, then the index build is not stopped. | An index build is not stopped if there is insufficient available disk space. |

#### Commit Quorum

**Note: Requires featureCompatibilityVersion 4.4+**

Each [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod.md#mongodb-binary-bin.mongod) in the replica set or sharded cluster *must* have [featureCompatibilityVersion](https://www.mongodb.com/docs/manual/reference/command/setFeatureCompatibilityVersion.md#std-label-set-fcv) set to at least `4.4` to start index builds simultaneously across replica set members.

Index builds on a replica set or sharded cluster build simultaneously across all data-bearing replica set members. For sharded clusters, the index build occurs only on shards containing data for the collection being indexed. The primary requires a minimum number of data-bearing [`voting`](https://www.mongodb.com/docs/manual/reference/replica-configuration.md#mongodb-rsconf-rsconf.members-n-.votes) members (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. See [Index Builds in Replicated Environments](https://www.mongodb.com/docs/manual/core/index-creation.md#std-label-index-operations-replicated-build) for more information.

To set the [commit quorum](https://www.mongodb.com/docs/manual/reference/command/createIndexes.md#std-label-createIndexes-cmd-commitQuorum), use [`createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) to specify the `commitQuorum` value.

`commitQuorum` specifies how many data-bearing voting members, or which voting members, including the primary, must be prepared to commit the index build before the primary will execute the commit. The default commit quorum is `votingMembers`, which means all data-bearing members.

## 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.

**Note:**

Documents in the `movies` collection contain additional fields not shown here.

### Create an Ascending Index on a Single Field

The following example creates an ascending index on the field `title`.

```javascript
db.movies.createIndex( { title: 1 } )

```

If the `keys` document specifies more than one field, then [`createIndex()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#mongodb-method-db.collection.createIndex) creates a [compound index.](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-compound-index)

### Create an Index on Multiple Fields

The following example creates a compound index on the `year`, `runtime`, and `title` fields:

```javascript
db.movies.createIndex( { year: 1, runtime: 1, title: 1 } )

```

The following example creates a compound index on the `title` field (in ascending order) and the `runtime` field (hashed):

```javascript
db.movies.createIndex( { title: 1, runtime: "hashed" } )

```

For more information on hashed indexes, see [Hashed Indexes.](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-hashed.md#std-label-index-type-hashed)

### Create Indexes with Collation

Use the following code to create an index on the `movies` collection of the `sample_mflix` database with the collation locale `"fr"` for string comparisons:

```javascript
db.movies.createIndex( { title: 1 }, { collation: { locale: "fr" } } )

```

The following query, which specifies the same collation as the index, can use the index:

```javascript
db.movies.find( 
    { title: "Les Misèrables" },
    { title: 1, year: 1 }
).collation( { locale: "fr" } )

```

However, the following query operation, which by default uses the "simple" binary collator, cannot use the index and requires a `COLLSCAN`.

```javascript
db.movies.find( { title: "Les Misèrables" }, { title: 1 , year: 1 } )

```

For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys.

For example, you can use the following code to create a compound index on the `movies` collection of the `sample_mflix` database specifying the numeric fields `year` and `metacritic` and the string field `title`. The index also specifies the collation locale `"fr"` for string comparisons:

```javascript
db.movies.createIndex(
    { year: 1, metacritic: 1, title: 1 },
    { collation: { locale: "fr" } }
)

```

The following operations, which use `"simple"` binary collation for string comparisons, can use the index:

```javascript
db.movies.find( 
    { year: 2012 }, 
    { title: 1, year: 1, metacritic: 1 } 
).sort( { title: 1 } )

```

```javascript
db.movies.find( 
    { year: 2012, metacritic: { $gt: Decimal128( "50" ) } },
    { title: 1, year: 1, metacritic: 1 }
).sort( { title: 1 } )

```

The following operation, which uses `"simple"` binary collation for string comparisons on the indexed `title` field, can use the index to fulfill only the `year: 2012` portion of the query:

```javascript
db.movies.find( { year: 2012, title: "Les Misèrables" }, { year: 1, title: 1 } )

```

To confirm whether a query used an index, run the query with the [`explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) option.

**Important:**

Matches against document keys, including embedded document keys, use simple binary comparison. This means that a query for a key like "type.café" will not match the key "type.cafe", regardless of the value you set for the [strength](https://www.mongodb.com/docs/manual/reference/collation.md#std-label-collation-parameter-strength) parameter.

### Create a Wildcard Index on a Single Field Path

The following operation creates a wildcard index on the `awards` field:

```javascript
db.movies.createIndex( { "awards.$**": 1 } )

```

With this wildcard index, MongoDB indexes all scalar values of `awards`. If the field is a nested document or array, the wildcard index recurses into the document or array and indexes all scalar fields in the document or array.

The wildcard index can support arbitrary single-field queries on `awards` or one of its nested fields:

```javascript
db.movies.find( { "awards.wins": { $gt: 1 } }, { title: 1 } )

```

```javascript
db.movies.find( { "awards.nominations": { $gt: 5 } }, { title: 1 } )

```

### Create a Wildcard Index on All Field Paths

The following operation creates a wildcard index on all scalar fields (excluding the `_id` field):

```javascript
db.movies.createIndex( { "$**": 1 } )

```

With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document or array and indexes all scalar fields in the document or array.

The created index can support queries on any arbitrary field within documents in the collection:

```javascript
db.movies.find( { runtime: { $gt: 300 } }, { title: 1 } )

```

```javascript
db.movies.find( { "awards.nominations": { $gt: 5 } }, { title: 1 } )

```

#### Include Specific Fields in Wildcard Index Coverage

The following operation creates a wildcard index and uses the `wildcardProjection` option to include only scalar values of the `tomatoes.viewer` and `tomatoes.critic` fields in the index.

```javascript
db.movies.createIndex( 
    { "$**": 1 },
    {
      "wildcardProjection": {
          "tomatoes.viewer": 1,
          "tomatoes.critic": 1
      }
    }
)

```

The pattern `"$**"` includes all fields in the document. Use the `wildcardProjection` field to limit the index to fields you specify. For complete documentation on `wildcardProjection`, see [Options for `wildcard` indexes.](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-createIndex-method-wildcard-option)

If a field is a nested document or array, the wildcard index recurses into it and indexes all scalar fields in the document or array.

The wildcard index supports queries on any scalar field included in the `wildcardProjection`:

```javascript
db.movies.find( { "tomatoes.viewer.rating": { $gt: 4 } }, { title: 1 } )

```

**Note:**

Wildcard indexes do not support mixing inclusion and exclusion statements in the `wildcardProjection` document *except* when explicitly including the `_id` field. For more information on `wildcardProjection`, see the [parameter documentation](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndexes.md#std-label-createIndexes-method-wildcard-option).

#### Omit Specific Fields from Wildcard Index Coverage

This example uses a wildcard index and a `wildcardProjection` document to index the scalar fields for each document in the collection.

The wildcard index excludes the `tomatoes.viewer` and `tomatoes.critic` fields:

```javascript
db.movies.createIndex( 
    { "$**": 1 },
    {
      "wildcardProjection": {
          "tomatoes.viewer": 0,
          "tomatoes.critic": 0
      }
    }
)

```

The wildcard pattern `"$**"` includes all of the fields in the document. However, the `wildcardProjection` field excludes the specified fields from the index.

For complete documentation on `wildcardProjection`, see [Options for `wildcard` indexes.](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-createIndex-method-wildcard-option)

If a field is a nested document or array, the wildcard index recurses into the document or array and indexes all scalar fields in the document or array.

The index can support queries on any scalar field **except** those excluded by `wildcardProjection`:

```javascript
db.movies.find( { "tomatoes.viewer.rating": { $gt: 3 } }, { title: 1 } )

```

**Note:**

Wildcard indexes do not support mixing inclusion and exclusion statements in the `wildcardProjection` document *except* when explicitly including the `_id` field. For more information on `wildcardProjection`, see the [parameter documentation](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndexes.md#std-label-createIndexes-method-wildcard-option).

### Create Index With Commit Quorum

The following operation creates an index with a [commit quorum](https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex.md#std-label-createIndex-method-commitQuorum) of `"majority"`, or a simple majority of data-bearing voting members:

```javascript
db.movies.createIndex(
    { "title": 1 },
    { },
    "majority"
)

```

The [primary](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-primary) marks index build as ready only after a simple majority of data-bearing voting members "vote" to commit the index build. For more information on index builds and the voting process, see [Index Builds in Replicated Environments.](https://www.mongodb.com/docs/manual/core/index-creation.md#std-label-index-operations-replicated-build)

## Additional Information

- The [Indexes](https://www.mongodb.com/docs/manual/indexes.md#std-label-indexes) section of this manual for full documentation of indexes and indexing in MongoDB.

- [`db.collection.getIndexes()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.getIndexes.md#mongodb-method-db.collection.getIndexes) to view the specifications of existing indexes for a collection.

- [Text Indexes on Self-Managed Deployments](https://www.mongodb.com/docs/manual/core/indexes/index-types/index-text.md#std-label-index-type-text) for details on creating `text` indexes.

- [Geospatial Indexes](https://www.mongodb.com/docs/manual/geospatial-queries.md#std-label-index-feature-geospatial) for geospatial queries.

- [TTL Indexes](https://www.mongodb.com/docs/manual/core/index-ttl.md#std-label-index-feature-ttl) for expiration of data.
