On this page本页内容
db.collection.
createIndexes
([keyPatterns, ]options, commitQuorum)¶mongo
Shell Method
This page documents the 本页记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
Creates one or more indexes on a collection.在集合上创建一个或多个索引。
db.collection.createIndexes()
takes the following parameters:采用以下参数:
keyPatterns |
document |
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 more information on creating wildcard indexes, see Wildcard Indexes. |
options |
document | |
commitQuorum | integer |
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:
|
The db.collection.createIndexes()
is a wrapper around the createIndexes
command.db.collection.createIndexes()
是createIndexes
命令的包装器。
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 options
document contains a set of options that control the creation of the indexes. options
文档包含一组控制索引创建的选项。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 mutiple option documents the 但是,如果指定多个选项文档,db.collection.createIndexes()
operation will fail.db.collection.createIndexes()
操作将失败。
Consider the following 考虑下面的db.collection.createIndexes()
operation:db.collection.createIndexes()
操作:
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.{ unique: true }, { sparse: true, expireAfterSeconds: 3600 }
,则索引创建操作将失败。
Important重要的
When you specify options to db.collection.createIndexes()
, the options apply to all of the specified indexes. For example, if you specify a collation option, all of the created indexes will include that collation.
db.collection.createIndexes()
will return an error if you attempt to create indexes with incompatible options or too many arguments. 如果尝试使用不兼容的选项或太多参数创建索引,将返回错误。Refer to the option descriptions for more information.有关更多信息,请参阅选项说明。
The following options are available for all index types unless otherwise specified:以下选项适用于所有索引类型,除非另有规定:
background |
boolean |
|
unique |
boolean |
|
name |
string |
Starting in version 4.2, for featureCompatibilityVersion set to Options specified to |
partialFilterExpression |
document |
You can specify a
|
sparse |
boolean |
|
expireAfterSeconds |
integer | |
hidden | boolean |
|
storageEngine |
document |
|
collation |
document |
|
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.text
、2d
或geoHaystack
索引,必须在创建索引时显式指定{collation: {locale: "simple"} }
。
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. strength
指定为1
或2
,可以创建不区分大小写的索引。Index with a collation 排序规则strength
of 1
is both diacritic- and case-insensitive.strength
为1
的索引既不区分重音,也不区分大小写。
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"
.myColl
在排序规则区域设置为"fr"
的字符串字段category
上有一个索引。
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:myColl
在数字字段score
和price
以及字符串字段类别上有一个复合索引;索引是使用排序规则区域设置"fr"
创建的,用于字符串比较:
The following operations, which use 以下使用"simple"
binary collation for string comparisons, can use the index:"simple"
二进制排序规则进行字符串比较的操作可以使用索引:
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:"simple"
二进制排序规则对索引category
字段进行字符串比较,可以使用索引只完成查询的score: 5
部分:
text
Indexestext
索引选项¶The following options are available for text indexes only:以下选项仅适用于text
索引:
weights |
document | text 索引,包含字段和权重对的文档。1 .1 。 |
default_language |
string | text 索引,确定停止词列表以及词干分析器和标记器规则的语言。english .english 。 |
language_override |
string | language . language 。 |
textIndexVersion |
integer |
|
2dsphere
Indexes2dsphere
索引的选项¶The following option is available for 2dsphere indexes only:以下选项仅适用于2dsphere
索引:
2dsphereIndexVersion |
integer |
|
2d
Indexes2d
索引的选项¶The following options are available for 2d indexes only:以下选项仅适用于2d
索引:
bits |
integer |
|
min |
number | 2d 索引,指经度和纬度值的下包容边界。-180.0 .-180.0 。 |
max |
number | 2d 索引,是经度和纬度值的上包容边界。180.0 .180.0 。 |
geoHaystack
IndexesgeoHaystack
索引选项¶The following option is available for geoHaystack indexes only:以下选项仅适用于geoHaystack
索引:
bucketSize |
number |
|
wildcard
indexeswildcard
索引选项¶The following option is available for wildcard indexes only:以下选项仅适用于wildcard
索引:
wildcardProjection |
document |
|
Changed in version 4.2.在版本4.2中更改。
For featureCompatibilityVersion 对于featureCompatibilityVersion "4.2"
, db.collection.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. "4.2"
,db.collection.createIndexes()
使用优化的生成过程,在索引生成的开始和结束时获取并持有指定集合的独占锁。All subsequent operations on the collection must wait until 集合上的所有后续操作都必须等待db.collection.createIndexes()
releases the exclusive lock. db.collection.createIndexes()
释放独占锁。db.collection.createIndexes()
allows interleaving read and write operations during the majority of the index build.允许在大多数索引生成期间交错执行读写操作。
For featureCompatibilityVersion 对于featureCompatibilityVersion "4.0"
, db.collection.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. "4.0"
,db.collection.createIndexes()
使用4.2之前的索引生成过程,默认情况下,该过程会在整个生成过程中获得父数据库的独占锁。The pre-4.2 build process blocks all operations on the database and all its collections until the operation completed. 4.2版本之前的构建过程会阻止数据库及其所有集合上的所有操作,直到操作完成。background
indexes do not take an exclusive lock.background
索引不采用独占锁。
For more information on the locking behavior of 有关db.collection.createIndexes()
, see Index Builds on Populated Collections.db.collection.createIndexes()
锁定行为的更多信息,请参阅基于填充集合的索引构建。
If you call 如果为已经存在的一个或多个索引调用db.collection.createIndexes()
for an index or indexes that already exist, MongoDB does not recreate the existing index or indexes.db.collection.createIndexes()
,MongoDB不会重新创建现有的一个或多个索引。
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.要创建具有相同键模式但不同排序规则的索引,必须提供唯一的索引名。
For MongoDB 2.6 through MongoDB versions with featureCompatibilityVersion (fCV) set to 对于featureCompatibilityVersion(fCV)设置为"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
."4.0"
或更早版本的MongoDB 2.6到MongoDB版本,如果现有文档的索引项超过最大索引键长度,MongoDB将不会在集合上创建索引。
New in version 4.2.版本4.2中的新功能。
_id
field by default. _id
字段。_id
field in the wildcard index, you must explicitly include it in the wildcardProjection
document:_id
字段,必须在wildcardProjection
文档中明确包含它:
With the exception of explicitly including 除了显式包含_id
field, you cannot combine inclusion and exclusion statements in the wildcardProjection
document._id
字段外,不能在wildcardProjection
文档中组合包含和排除语句。
mongod
featureCompatibilityVersion must be 4.2
to create wildcard indexes. mongod
featureCompatibilityVersion必须为4.2
才能创建通配符索引。Note
Wildcard Indexes are distinct from and incompatible with Wildcard Text Indexes. 通配符索引不同于通配符文本索引,并且与通配符文本索引不兼容。Wildcard indexes cannot support queries using the 通配符索引无法支持使用$text
operator.$text
运算符的查询。
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.在版本4.4中更改。
Starting in MongoDB 4.4 with feature compatibility version (fcv) 从功能兼容版本(fcv)"4.4"
, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction."4.4"
的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。
To use 要在事务中使用db.collection.createIndexes()
in a transaction, the transaction must use read concern "local"
. db.collection.createIndexes()
,该事务必须使用"local"
读关注点。If you specify a read concern level other than 如果指定的读取关注级别不是"local"
, the transaction fails."local"
,则事务失败。
See also参阅
db.collection.createIndex()
for examples of various index specifications.有关各种索引规范的示例。
Consider a 考虑一个包含类似以下文件的restaurants
collection containing documents that resemble the following:restaurants
集合:
The following example creates two indexes on the 下面的示例在restaurants
collection: an ascending index on the borough
field and a 2dsphere index on the location
field.restaurants
集合上创建两个索引:在borough
字段上创建升序索引,在location
字段上创建2dsphere
索引。
The following example creates two indexes on the 以下示例在products
collection: an ascending index on the manufacturer
field and an ascending index on the category
field. products
集合上创建两个索引:manufacturer
字段上的升序索引和category
字段上的升序索引。Both indexes use a collation that specifies the locale 这两个索引都使用排序规则来指定区域设置fr
and comparison strength 2
:fr
和比较强度2
:
For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. 对于使用相同排序规则的索引键的查询或排序操作,MongoDB可以使用索引。For details, see Collation and Index Use.有关详细信息,请参阅排序规则和索引使用。
New in version 4.2:4.2版中新增:The mongod
featureCompatibilityVersion must be 4.2
to create wildcard indexes. mongod
featureCompatibilityVersion必须为4.2
才能创建通配符索引。For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 4.4 Deployments.有关设置fCV的说明,请参阅在MongoDB 4.4部署上设置功能兼容性版本。
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. products_catalog
,其中文档可以包含一个product_attributes
字段。The product_attributes
field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
The following operation creates a wildcard index on the 以下操作在product_attributes
field:product_attributes
字段上创建通配符索引:
With this wildcard index, MongoDB indexes all scalar values of 通过这个通配符索引,MongoDB对product_attributes
. 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:product_attributes
或其中一个嵌套字段的任意单字段查询:
Note
The path-specific wildcard index syntax is incompatible with the 路径特定的通配符索引语法与wildcardProjection
option. wildcardProjection
选项不兼容。See the parameter documentation for more information.有关更多信息,请参阅参数文档。
Consider a collection 考虑一个集合products_catalog
where documents may contain a product_attributes
field. products_catalog
,其中文档可以包含一个product_attributes
字段。The product_attributes
field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
The following operation creates a wildcard index on all scalar fields (excluding the 以下操作在所有标量字段(不包括_id
field):_id
字段)上创建通配符索引:
With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. 通过这个通配符索引,MongoDB为集合中每个文档的所有标量字段编制索引。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. _id
字段。To include the 要在通配符索引中包含_id
field in the wildcard index, you must explicitly include it in the wildcardProjection
document. _id
字段,必须在wildcardProjection
(通配符投影)文档中显式包含它。See parameter documentation for more information.有关更多信息,请参阅参数文档。
Consider a collection 考虑一个集合products_catalog
where documents may contain a product_attributes
field. products_catalog
,其中文档可以包含一个product_attributes
字段。The product_attributes
field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
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.wildcardProjection
选项仅包括索引中product_attributes.elements
和product_attributes.resistance
字段的标量值。
While the key pattern 虽然键模式"$**"
covers all fields in the document, the wildcardProjection
field limits the index to only the included fields. "$**"
涵盖文档中的所有字段,但wildcardProjection
字段将索引仅限于包含的字段。For complete documentation on 有关wildcardProjection
, see Options for wildcard indexes.wildcardProjection
的完整文档,请参阅通配符索引选项。
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
:wildcardProjection
中包含的任何标量字段的查询:
Note
Wildcard indexes do not support mixing inclusion and exclusion statements in the 通配符索引不支持在wildcardProjection
document except when explicitly including the _id
field. wildcardProjection
文档中混合包含和排除语句,除非显式包含_id
字段。For more information on 有关wildcardProjection
, see the parameter documentation.wildcardProjection
的更多信息,请参阅参数文档。
Consider a collection 考虑一个集合products_catalog
where documents may contain a product_attributes
field. products_catalog
,其中文档可以包含一个product_attributes
字段。The product_attributes
field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
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:wildcardProjection
文档为集合中每个文档的所有标量字段编制索引,不包括product_attributes.elements
字段和product_attributes.resistance
字段:
While the key pattern 虽然键模式"$**"
covers all fields in the document, the wildcardProjection
field excludes the specified fields from the index. "$**"
涵盖文档中的所有字段,但wildcardProjection
字段将指定字段从索引中排除。For complete documentation on 有关wildcardProjection
, see Options for wildcard indexes.wildcardProjection
的完整文档,请参阅通配符索引选项
。
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
:wildcardProjection
排除的字段除外:
Note
Wildcard indexes do not support mixing inclusion and exclusion statements in the 通配符索引不支持在wildcardProjection
document except when explicitly including the _id
field. wildcardProjection
文档中混合包含和排除语句,除非显式包含_id
字段。For more information on 有关wildcardProjection
, see the parameter documentation.wildcardProjection
的更多信息,请参阅参数文档。
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.mongod
必须将featureCompatibilityVersion设置为至少4.4
,才能在副本集成员之间同时启动索引构建。
MongoDB 4.4 running 运行featureCompatibilityVersion: "4.2"
builds indexes on the primary before replicating the index build to secondaries.featureCompatibilityVersion: "4.2"
的MongoDB 4.4在将索引构建复制到辅助库之前在主库上构建索引。
Starting with MongoDB 4.4, index builds on a replica set or sharded cluster build simultaneously across all data-bearing replica set members. 从MongoDB 4.4开始,索引构建在副本集上,或者在所有数据承载副本集成员之间同时构建分片集群。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 primary需要最少数量的数据承载voting
members (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. voting
成员(即commit quorum),包括其自身,这些成员必须在将索引标记为可供使用之前完成构建。See Index Builds in Replicated Environments for more information.有关更多信息,请参阅复制环境中的索引构建。
Specify the commitQuorum parameter 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. createIndexes
操作指定commitQuorum
参数,以设置包含数据的投票成员(即commit quorum)的最小数量,包括主成员,主成员必须在主成员将索引标记为就绪之前完成索引生成。The default commit quorum is 默认提交仲裁为votingMembers,或所有数据承载投票副本集成员。votingMembers
, or all data-bearing voting replica set members.
The following operation creates an index with a commit quorum of 以下操作将创建提交仲裁为"majority"
:"majority"
的索引:
The primary marks index build as ready only after a simple majority of data-bearing voting members “vote” to commit the index build. 只有在携带数据的大多数投票成员“投票”提交索引构建后,primary才会将索引构建标记为就绪。For more information on index builds and the voting process, see Index Builds in Replicated Environments.有关索引生成和投票过程的更多信息,请参阅复制环境中的索引生成。
For additional information about indexes, refer to:有关索引的更多信息,请参阅:
db.collection.getIndexes()
text
indexes.text
索引的详细信息。