- Reference >
mongo
Shell Methods >- Collection Methods >
- db.collection.createIndex()
db.collection.createIndex()¶
On this page
Definition¶
-
db.collection.
createIndex
(keys, options, commitQuorum)¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.Creates indexes on collections.
db.collection.createIndex()
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
. Starting in 3.6, you cannot specify*
as the index name.MongoDB supports several different index types including text, geospatial, and hashed indexes. See index types for more information.
Changed in version 4.2: MongoDB 4.2 wildcard indexes support workloads where users query against custom fields or a large variety of fields in a collection:
To create a wildcard index on all fields and subfields in a document, specify
{ "$**" : 1 }
as the index key. You cannot specify a descending index key when creating a wildcard index.You can also either include or exclude specific fields and their subfields from the index using the optional
wildcardProjection
parameter.Wildcard indexes omit the
_id
field by default. To include the_id
field in the wildcard index, you must explicitly include it in thewildcardProjection
document:With the exception of explicitly including
_id
field, you cannot combine inclusion and exclusion statements in thewildcardProjection
document.You can create a wildcard index on a specific field and its subpaths by specifying the full path to that field as the index key and append
"$**"
to the path:{ "path.to.field.$**" : 1 }
You cannot specify a descending index key when creating a wildcard index.
The path-specific wildcard index syntax is incompatible with the
wildcardProjection
option. You cannot specify additional inclusions or exclusions on the specified path.
The wildcard index key must use one of the syntaxes listed above. For example, you cannot specify a compound index key. For more complete documentation on wildcard indexes, including restrictions on their creation, see Wildcard Index Restrictions.
The
mongod
featureCompatibilityVersion must be4.2
to create wildcard indexes. For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 4.4 Deployments.For examples of wildcard index creation, see Create a Wildcard Index.
options
document Optional. A document that contains a set of options that controls the creation of the index. See Options for details. 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 before the primary marks the
indexes
as ready. A “voting” member is any replica set member wheremembers[n].votes
is greater than0
.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.0
- Disables quorum-voting behavior. Members start the index build simultaneously but do not vote or wait for quorum before completing the index build. If you start an index build with a commit quorum of0
, you cannot later modify the commit quorum usingsetIndexCommitQuorum
.- A replica set tag name.
New in version 4.4.
The
db.collection.createIndex()
is a wrapper around thecreateIndexes
command.To minimize the impact of building an index on replica sets and sharded clusters, use a rolling index build procedure as described on Rolling Index Builds on Replica Sets.
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.
Changed in version 3.4: Added support for collation option.
Options for All Index Types¶
The following options are available for all index types unless otherwise specified:
Parameter | Type | Description |
---|---|---|
background |
boolean | Optional. Deprecated in MongoDB 4.2.
|
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 The option is unavailable for hashed indexes. |
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. Changed in MongoDB 4.2 Starting in version 4.2, for featureCompatibilityVersion set to |
partialFilterExpression |
document | Optional. If specified, the index only references documents that match the filter expression. See Partial Indexes for more information. A filter expression can include:
You can specify a New in version 3.2. |
sparse |
boolean | Optional. If The following index types are sparse by default and ignore this option: For a compound index that includes Changed in version 3.2: Starting in MongoDB 3.2, MongoDB provides the option to create partial indexes. Partial indexes offer a superset of the functionality of sparse indexes. If you are using MongoDB 3.2 or later, partial indexes should be preferred over sparse indexes. |
expireAfterSeconds |
integer | Optional. Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. See Expire Data from Collections by Setting TTL for more information on this functionality. This applies only to TTL indexes. |
hidden | boolean | Default is To use the New in version 4.4. |
storageEngine |
document | Optional. Allows users to configure the storage engine on a per-index basis when creating an index. The Storage engine configuration options specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines. |
Option for Collation¶
New in version 3.4.
Warning
Collation is not supported in MongoDB 3.2 and earlier versions. In MongoDB 3.2 and earlier versions, do not create indexes with the unsupported collation option as this will block the upgrade to 3.4, which enforces a stricter validation of index options.
Parameter | Type | Description |
---|---|---|
collation |
document | Optional. Specifies the collation for the index. 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:
The collation option has the following syntax: When specifying collation, the New in version 3.4. |
The following indexes only support simple binary comparison and do not support collation:
- text indexes,
- 2d indexes, and
- geoHaystack indexes.
Tip
To create a text
, a 2d
, or a geoHaystack
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.
Unlike other index options, 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. That is, an index with a collation cannot support an operation that performs string comparisons on the indexed fields if the operation specifies a different collation.
For example, the collection myColl
has an index on a string
field category
with the collation locale "fr"
.
The following query operation, which specifies the same collation as the index, can use the index:
However, the following query operation, which by default uses the “simple” binary collator, cannot use the index:
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, the collection myColl
has a compound index on the
numeric fields score
and price
and the string field
category
; the index is created with the collation locale
"fr"
for string comparisons:
The following operations, which use "simple"
binary collation
for string comparisons, can use the index:
The following operation, which uses "simple"
binary collation
for string comparisons on the indexed category
field, can use
the index to fulfill only the score: 5
portion of the query:
Options for text
Indexes¶
The following options are available for text indexes only:
Parameter | Type | Description |
---|---|---|
weights |
document | Optional. For 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
Control Search Results with Weights to adjust the scores.
The default value is 1 . |
default_language |
string | Optional. For text indexes, the language that
determines the list of stop words and the rules for the stemmer and
tokenizer. See Text Search Languages for the available
languages and Specify a Language for Text Index for
more information and examples. The default value is english . |
language_override |
string | Optional. For 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
Use any Field to Specify the Language for a Document for an example. |
textIndexVersion |
integer | Optional. The For available versions, see Versions. |
Options for 2dsphere
Indexes¶
The following option is available for 2dsphere indexes only:
Parameter | Type | Description |
---|---|---|
2dsphereIndexVersion |
integer | Optional. The For the available versions, see Versions. |
Options for 2d
Indexes¶
The following options are available for 2d indexes only:
Parameter | Type | Description |
---|---|---|
bits |
integer | Optional. For 2d indexes, the number of precision of the stored geohash value of the location data. The |
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 geoHaystack
Indexes¶
The following option is available for geoHaystack indexes only:
Parameter | Type | Description |
---|---|---|
bucketSize |
number | For geoHaystack indexes, specify the number of units within which to group the location values; i.e. group in the same bucket those location values that are within the specified number of units to each other. The value must be greater than 0. |
Options for wildcard
indexes¶
The following option is available for wildcard indexes only:
Parameter | Type | Description |
---|---|---|
wildcardProjection |
document | Optional. Allows users to include or exclude specific field paths from
a wildcard index using the
The The
Wildcard indexes omit the With the exception of explicitly including |
Behaviors¶
Concurrency¶
Changed in version 4.2.
For featureCompatibilityVersion "4.2"
, db.collection.createIndex()
uses an optimized build process that obtains and holds an exclusive lock on
the specified collection at the start and end of the index build. All
subsequent operations on the collection must wait until db.collection.createIndex()
releases
the exclusive lock. db.collection.createIndex()
allows interleaving read and write
operations during the majority of the index build.
For featureCompatibilityVersion "4.0"
, db.collection.createIndex()
uses the pre-4.2 index build process which by default obtains an exclusive
lock on the parent database for the entire duration of the build process. The
pre-4.2 build process blocks all operations on the database and all its
collections until the operation completed. background
indexes do not take
an exclusive lock.
For more information on the locking behavior of db.collection.createIndex()
, see
Index Builds on Populated Collections.
Recreating an Existing Index¶
If you call db.collection.createIndex()
for an index that
already exists, MongoDB does not recreate the index.
Index Options¶
Collation Option¶
Unlike other index options, 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.
Index Key Length Limit¶
For MongoDB 2.6 through MongoDB versions with
featureCompatibilityVersion (fCV) set to "4.0"
or
earlier, MongoDB will not create an index on a collection if the
index entry for an existing document exceeds the Maximum Index Key Length
.
Transactions¶
Changed in version 4.4.
Starting in MongoDB 4.4 with feature compatibility version
(fcv) "4.4"
, you can create collections and indexes
inside a multi-document transaction if the transaction is
not a cross-shard write transaction.
To use db.collection.createIndex()
in a transaction, the transaction must use read
concern "local"
. If you specify a read concern level
other than "local"
, the transaction fails.
Examples¶
Create an Ascending Index on a Single Field¶
The following example creates an ascending index on the field
orderDate
.
If the keys
document specifies more than one field, then
createIndex()
creates a compound
index.
Create an Index on a Multiple Fields¶
The following example creates a compound index on the
orderDate
field (in ascending order) and the zipcode
field (in descending order.)
Changed in version 4.4: Starting in MongoDB 4.4, compound indexes can include a single
hashed field. Compound hashed indexes
require featureCompatibilityVersion set to 4.4
.
The following example creates a compound index on the state
field
(in ascending order) and the zipcode
field (hashed):
The order of fields in a compound index is important for supporting
sort()
operations using the index.
Create Indexes with Collation Specified¶
New in version 3.4.
The following example creates an index named category_fr
. The
example creates the index with the collation that specifies the locale fr
and
comparison strength 2
:
The following example creates a compound index named
date_category_fr
with a collation.
The collation applies only to the index keys with string values.
The collation applies to the indexed keys whose values are string.
For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. For details, see Collation and Index Use.
Create a Wildcard Index¶
New in version 4.2.
The mongod
featureCompatibilityVersion must be 4.2
to
create wildcard indexes. For instructions on setting the fCV, see
Set Feature Compatibility Version on MongoDB 4.4 Deployments.
Wildcard indexes omit the
_id
field by default. To include the_id
field in the wildcard index, you must explicitly include it in thewildcardProjection
document:With the exception of explicitly including
_id
field, you cannot combine inclusion and exclusion statements in thewildcardProjection
document.Wildcard indexes do not support the following index types or properties:
Note
Wildcard Indexes are distinct from and incompatible with Wildcard Text Indexes. Wildcard indexes cannot support queries using the
$text
operator.For complete documentation on wildcard index restrictions, see Wildcard Index Restrictions.
For complete documentation on Wildcard Indexes, see Wildcard Indexes.
The following lists examples of wildcard index creation:
- Create a Wildcard Index on a Single Field Path
- Create a Wildcard Index on All Field Paths
- Include Specific Fields in Wildcard Index Coverage
- Omit Specific Fields from Wildcard Index Coverage
Create a Wildcard Index on a Single Field Path¶
Consider a collection products_catalog
where documents may contain a
product_attributes
field. The product_attributes
field can
contain arbitrary nested fields, including embedded
documents and arrays:
The following operation creates a wildcard index on the
product_attributes
field:
With this wildcard index, MongoDB indexes all scalar values of
product_attributes
. If the field is a nested document or array, the
wildcard index recurses into the document/array and indexes all scalar
fields in the document/array.
The wildcard index can support arbitrary single-field queries on
product_attributes
or one of its nested fields:
Note
The path-specific wildcard index syntax is incompatible with the
wildcardProjection
option. See the parameter documentation for more
information.
Create a Wildcard Index on All Field Paths¶
Consider a collection products_catalog
where documents may contain a
product_attributes
field. The product_attributes
field can
contain arbitrary nested fields, including embedded
documents and arrays:
The following operation creates a wildcard index on all scalar fields
(excluding the _id
field):
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/array and indexes all scalar fields in the document/array.
The created index can support queries on any arbitrary field within documents in the collection:
Note
Wildcard indexes omit the _id
field by default. To include the
_id
field in the wildcard index, you must explicitly include it
in the wildcardProjection
document. See parameter documentation for
more information.
Include Specific Fields in Wildcard Index Coverage¶
Consider a collection products_catalog
where documents may contain a
product_attributes
field. The product_attributes
field can
contain arbitrary nested fields, including embedded
documents and arrays:
The following operation creates a wildcard index and uses
the wildcardProjection
option to include only scalar values of the
product_attributes.elements
and product_attributes.resistance
fields in the index.
While the key pattern "$**"
covers all fields in the document, the
wildcardProjection
field limits the index to only the included
fields. For complete documentation on wildcardProjection
, see
Options for wildcard indexes.
If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.
The created index can support queries on any scalar field
included in the wildcardProjection
:
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.
Omit Specific Fields from Wildcard Index Coverage¶
Consider a collection products_catalog
where documents may contain a
product_attributes
field. The product_attributes
field can
contain arbitrary nested fields, including embedded
documents and arrays:
The following operation creates a wildcard index and uses
the wildcardProjection
document to index all scalar fields
for each document in the collection, excluding the
product_attributes.elements
and product_attributes.resistance
fields:
While the key pattern "$**"
covers all fields in the document, the
wildcardProjection
field excludes the specified fields from the
index. For complete documentation on wildcardProjection
, see
Options for wildcard indexes.
If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.
The created index can support queries on any scalar field except
those excluded by wildcardProjection
:
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.
Create Index With Commit Quorum¶
Requires featureCompatibilityVersion
4.4+
Each mongod
in the replica set or sharded cluster
must have featureCompatibilityVersion set to at
least 4.4
to start index builds simultaneously across
replica set members.
MongoDB 4.4 running featureCompatibilityVersion: "4.2"
builds
indexes on the primary before replicating the index build to
secondaries.
Starting with MongoDB 4.4, 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
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 for more
information.
Specify the commitQuorum
parameter to the createIndex()
operation to set
the minimum number of data-bearing voting members (i.e commit
quorum), including the primary, which must complete the
index build before the primary marks the indexes as ready. The default
commit quorum is votingMembers
, or all data-bearing voting replica
set members.
The following operation creates an index with a commit quorum of "majority"
, or a
simple majority of data-bearing voting members:
The 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.
Additional Information¶
- The Indexes section of this manual for full documentation of indexes and indexing in MongoDB.
db.collection.getIndexes()
to view the specifications of existing indexes for a collection.- Text Indexes for details on creating
text
indexes. - Geospatial Indexes and geoHaystack Indexes for geospatial queries.
- TTL Indexes for expiration of data.