On this page本页内容
createIndexes
¶Builds one or more indexes on a collection.
The createIndexes
command takes the following form:
The createIndexes
command takes the following fields:
createIndexes |
string | The collection for which to create indexes. |
indexes |
array | Specifies the indexes to create. Each document in the array specifies a separate index. |
writeConcern |
document |
|
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 Supports the following values:
|
comment |
any |
A comment can be any valid BSON type (string, integer, object, array, etc).
|
Each document in the indexes
array can take the following fields:
key |
document | Specifies the index’s fields. For each field, specify a key-value pair in which the key is the name of the field to index and the value is either the index direction or index type. If specifying direction, specify MongoDB supports several different index types including text, geospatial, and hashed indexes. See index types for more information.
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 For examples of wildcard index creation, see Create a Wildcard Index. |
name |
string | A name that uniquely identifies the index. |
background |
boolean |
|
unique |
boolean |
Specify The option is unavailable for hashed indexes. |
partialFilterExpression |
document |
A filter expression can include:
You can specify a
|
sparse |
boolean |
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 | |
hidden | boolean | Default is To use the
|
storageEngine |
document |
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. |
weights |
document | 1 . |
default_language |
string | english . |
language_override |
string | language . See Use any Field to Specify the Language for a Document for an example. |
textIndexVersion |
integer |
For available versions, see Versions. |
2dsphereIndexVersion |
integer |
For the available versions, see Versions. |
bits |
integer |
The |
min |
number | -180.0 . |
max |
number | 180.0 . |
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. |
collation |
document |
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 When specifying collation, the
|
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 |
The mongo
shell provides the methods db.collection.createIndex()
and db.collection.createIndexes()
as wrappers for the createIndexes
command.
Changed in version 3.2:MongoDB disallows the creation of version 0 indexes. To upgrade existing version 0 indexes, see Version 0 Indexes.
Changed in MongoDB 4.2
Starting in version 4.2, for featureCompatibilityVersion set to "4.2"
or greater, MongoDB removes the Index Name Length
limit of 127 byte maximum. In previous versions or MongoDB versions with featureCompatibilityVersion (fCV) set to "4.0"
, index names must fall within the limit
.
Starting in version 4.2, the createIndexes
command and the mongo
shell helpers db.collection.createIndex()
and db.collection.createIndexes()
report an error if you create an index with one name, and then try to create the same index again but with another name.
In previous versions, MongoDB did not create the index again, but would return a response object with ok
value of 1
and a note that implied that the index was not recreated. For example:例如:
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.
To start an index build with a non-default commit quorum, specify the commitQuorum.
MongoDB 4.4 adds the setIndexCommitQuorum
command for modifying the commit quorum of an in-progress index build.
In MongoDB 4.2 and earlier, index builds on a replica set or sharded cluster build on the primary first before replicating to the secondaries. See Index Builds In Replicated Environments (4.2) for the MongoDB 4.2 index build behavior.
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.
The following indexes only support simple binary comparison and do not support collation:
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.
Changed in version 4.2.
For featureCompatibilityVersion "4.2"
, createIndexes
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 createIndexes
releases the exclusive lock. createIndexes
allows interleaving read and write operations during the majority of the index build.
For featureCompatibilityVersion "4.0"
, createIndexes
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 createIndexes
, see Index Builds on Populated Collections.
Changed in version 3.4:createIndexes
supports building one or more indexes on a collection. createIndexes
uses a combination of memory and temporary files on disk to complete index builds. The default limit on memory usage for createIndexes
is 200 megabytes (for versions 4.2.3 and later) and 500 (for versions 4.2.2 and earlier), shared between all indexes built using a single createIndexes
command. Once the memory limit is reached, createIndexes
uses temporary disk files in a subdirectory named _tmp
within the --dbpath
directory to complete the build.
You can override the memory limit by setting the maxIndexBuildMemoryUsageMegabytes
server parameter. Setting a higher memory limit may result in faster completion of index builds. However, setting this limit too high relative to the unused RAM on your system can result in memory exhaustion and server shutdown.
New in version 3.4.版本3.4中的新功能。
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.
If you have specified a collation at the collection level, then:
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.
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:
New in version 4.2.版本4.2中的新功能。
_id
field by default. To include the _id
field in the wildcard index, you must explicitly include it in the wildcardProjection
document:
With the exception of explicitly including _id
field, you cannot combine inclusion and exclusion statements in the wildcardProjection
document.
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.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 examples of wildcard index creation, see Create a Wildcard Index. For complete documentation on Wildcard Indexes, see Wildcard Indexes.
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 createIndexes
in a transaction, the transaction must use read concern "local"
. If you specify a read concern level other than "local"
, the transaction fails.
The following command builds two indexes on the inventory
collection of the products
database:
When the indexes successfully finish building, MongoDB returns a results document that includes a status of "ok" : 1
.
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.
For complete documentation on Wildcard Indexes, see Wildcard Indexes.
The following lists examples of wildcard index creation:
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.
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.
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 and their nested fields.
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.
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.
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.
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 option to the createIndexes
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.
The createIndexes
command returns a document that indicates the success of the operation. The document contains some but not all of the following fields, depending on outcome:
createIndexes.
createdCollectionAutomatically
¶If true
, then the collection didn’t exist and was created in the process of creating the index.
createIndexes.
numIndexesBefore
¶The number of indexes at the start of the command.
createIndexes.
numIndexesAfter
¶The number of indexes at the end of the command.
createIndexes.
ok
¶A value of 1
indicates the indexes are in place. A value of 0
indicates an error.
createIndexes.
note
¶This note
is returned if an existing index or indexes already exist. This indicates that the index was not created or changed.
createIndexes.
errmsg
¶Returns information about any errors.
createIndexes.
code
¶The error code representing the type of error.