db.collection.createIndex()
On this page
Definition定义Options选项Options for All Index Types所有索引类型的选项Option for Collation排序规则选项Options fortext
Indexestext
索引选项Options for2dsphere
Indexes2dsphere
索引的选项Options for2d
Indexes2d
索引的选项Options forgeoHaystack
IndexesgeoHaystack
索引的选项Options forwildcard
indexeswildcard
索引的选项Behaviors行为Recreating an Existing Index重新创建现有索引Index Options索引选项Transactions事务Examples实例Create an Ascending Index on a Single Field在单个字段上创建升序索引Create an Index on a Multiple Fields在多个字段上创建索引Create Indexes with Collation Specified创建指定排序规则的索引Create a Wildcard Index创建通配符索引Create Index With Commit Quorum使用提交法定人数创建索引Additional Information附加信息
Definition定义
db.collection.createIndex(keys, options, commitQuorum)
-
Important
mongosh Method
This page documents a本页记录了一个mongosh
method.mongosh
方法。This is not the documentation for database commands or language-specific drivers, such as Node.js.这不是数据库命令或特定语言驱动程序(如Node.js)的文档。For the database command, see the有关数据库命令,请参阅createIndexes
command.createIndexes
命令。For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档。For the legacy对于遗留的mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:mongo
shell文档,请参阅相应MongoDB Server版本的文档:Creates indexes on collections.在集合上创建索引。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.要最大限度地减少在副本集和分片集群上构建索引的影响,请使用滚动索引构建过程,如在副本集上滚动索引构建中所述。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
.1
;对于递减索引,请指定值-1
。An asterisk (星号(*
) is not a valid index name.*
)不是有效的索引名称。
MongoDB supports several different index types including text, geospatial, and hashed indexes. See index types for more information.
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 optionalwildcardProjection
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:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}With the exception of explicitly including除了显式包含_id
field, you cannot combine inclusion and exclusion statements in thewildcardProjection
document._id
字段外,您不能在wildcardProjection
文档中组合包含语句和排除语句。 -
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 6.0 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. - To create a wildcard index on all fields and subfields in a document, specify
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()
operation will fail.
Consider the following db.collection.createIndex()
operation:
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:
unique | boolean | Specify true to create a unique index. The default value is false .The option is unavailable for hashed indexes. |
name | string | |
partialFilterExpression | document | A filter expression can include:
partialFilterExpression option for all MongoDB index types. |
sparse | boolean | 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 for more information.The following index types are sparse by default and ignore this option: For a compound index that includes 2dsphere index key(s) along with keys of other types, only the 2dsphere index fields determine whether the index references a document.
Tip
Partial indexes offer a superset of the functionality of sparse indexes. Unless your application has a specific requirement, use partial indexes instead of sparse indexes. |
expireAfterSeconds | integer | 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 to avoid misconfiguration issues. The TTL index expireAfterSeconds value must be within 0 and 2147483647 inclusive. |
hidden | boolean | Optional. A flag that determines whether the index is hidden from the query planner. A hidden index is not evaluated as part of the query plan selection. Default is false . New in version 4.4. |
storageEngine | document | 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 during replication to support replica sets with members that use different storage engines. |
Option for Collation
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:
collation: { When specifying collation, the |
The following indexes only support simple binary comparison and do not support collation:
-
text indexes,
-
2d indexes, and
-
geoHaystack indexes.
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.
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. 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"
.
db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )
The following query operation, which specifies the same collation as the index, can use the index:
db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )
However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:
db.myColl.find( { category: "cafe" } )
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:
db.myColl.createIndex(
{ score: 1, price: 1, category: 1 },
{ collation: { locale: "fr" } } )
The following operations, which use "simple"
binary collation for string comparisons, can use the index:
db.myColl.find( { score: 5 } ).sort( { price: 1 } )
db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } )
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:
db.myColl.find( { score: 5, category: "cafe" } )
Options for text
Indexes
The following options are available for text indexes only:
weights | document | 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 .Starting in MongoDB 5.0, the weights option is only allowed for text indexes. |
default_language | string | 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 | 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 | text index version number. Users can use this option to override the default version number.For available versions, see Versions. |
Options for 2dsphere
Indexes
The following option is available for 2dsphere indexes only:
2dsphereIndexVersion | integer | 2dsphere index version number. Users can use this option to override the default version number.For the available versions, see Versions. |
Options for 2d
Indexes
The following options are available for 2d indexes only:
bits | integer | The bits value ranges from 1 to 32 inclusive. The default value is 26 . |
min | number | 2d indexes, the lower inclusive boundary for the longitude and latitude values. The default value is -180.0 . |
max | number | 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:
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. |
Removed in MongoDB 5.0
MongoDB 5.0 removes the deprecated geoHaystack index and geoSearch
command. Use a 2d index with $geoNear
or one of the supported geospatial query operators instead.
Upgrading your MongoDB instance to 5.0 and setting featureCompatibilityVersion to 5.0
will delete any pre-existing geoHaystack indexes.
Options for wildcard
indexes
The following option is available for wildcard indexes only:
wildcardProjection | document | { "$**" : 1} key pattern. This option is only valid if creating a wildcard index on all document fields. You cannot specify this option if creating a wildcard index on a specific field path and its subfields, e.g. { "path.to.field.$**" : 1 } The wildcardProjection option takes the following form:
wildcardProjection: { The
Wildcard indexes omit the { With the exception of explicitly including |
Behaviors行为
Recreating an Existing Index
If you call 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, 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 option can be changed without dropping and recreating the index. See Hidden Option.
To change the other index options, drop the existing index with db.collection.dropIndex()
before running 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
New in version 4.4.
To hide or unhide existing indexes, you can use the following mongosh
methods:
For example,
-
To change the
hidden
option for an index totrue
, use thedb.collection.hideIndex()
method:db.restaurants.hideIndex( { borough: 1, ratings: 1 } );
-
To change the
hidden
option for an index tofalse
, use thedb.collection.unhideIndex()
method:db.restaurants.unhideIndex( { borough: 1, city: 1 } );
See also: 另请参阅:
Transactions事务
Changed in version 4.4.
Starting in MongoDB 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.
See also: 另请参阅:
Examples实例
Create an Ascending Index on a Single Field
The following example creates an ascending index on the field orderDate
.
db.collection.createIndex( { orderDate: 1 } )
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.)
db.collection.createIndex( { orderDate: 1, zipcode: -1 } )
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):
db.collection.createIndex( { "state" : 1, "zipcode" : "hashed" } )
The order of fields in a compound index is important for supporting sort()
operations using the index.
See also: 另请参阅:
Create Indexes with Collation Specified
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
:
db.collection.createIndex(
{ category: 1 },
{ name: "category_fr", collation: { locale: "fr", 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.
db.collection.createIndex(
{ orderDate: 1, category: 1 },
{ name: "date_category_fr", collation: { locale: "fr", strength: 2 } }
)
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
The mongod
featureCompatibilityVersion must be 4.2
to create wildcard indexes. For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 6.0 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:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}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:
NoteWildcard 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
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:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
The following operation creates a wildcard index on the product_attributes
field:
use inventory
db.products_catalog.createIndex( { "product_attributes.$**" : 1 } )
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:
db.products_catalog.find( { "product_attributes.superFlight" : true } )
db.products_catalog.find( { "product_attributes.maxSpeed" : { $gt : 20 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )
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:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
The following operation creates a wildcard index on all scalar fields (excluding the _id
field):
use inventory
db.products_catalog.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/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:
db.products_catalog.find( { "product_price" : { $lt : 25 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )
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:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
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.
use inventory
db.products_catalog.createIndex(
{ "$**" : 1 },
{
"wildcardProjection" : {
"product_attributes.elements" : 1,
"product_attributes.resistance" : 1
}
}
)
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
:
db.products_catalog.find( { "product_attributes.elements" : { $eq: "Water" } } )
db.products_catalog.find( { "product_attributes.resistance" : "Bludgeoning" } )
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:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
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:
use inventory
db.products_catalog.createIndex(
{ "$**" : 1 },
{
"wildcardProjection" : {
"product_attributes.elements" : 0,
"product_attributes.resistance" : 0
}
}
)
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
:
db.products_catalog.find( { "product_attributes.maxSpeed" : { $gt: 25 } } )
db.products_catalog.find( { "product_attributes.superStrength" : true } )
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.
To set the commit quorum, use 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.
The following operation creates an index with a commit quorum of "majority"
, or a simple majority of data-bearing voting members:
db.getSiblingDB("examples").invoices.createIndex(
{ "invoices" : 1 },
{ },
"majority"
)
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 for geospatial queries.
-
TTL Indexes for expiration of data.