On this page本页内容
db.collection.
createIndex
(keys, 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 indexes on collections.在集合上创建索引。
db.collection.createIndex()
takes the following parameters:采用以下参数:
keys |
document |
|
options |
document | |
commitQuorum |
integer |
|
The db.collection.createIndex()
is a wrapper around the createIndexes
command.db.collection.createIndex()
是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 controls the creation of the index. 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.createIndex()
operation will fail.db.collection.createIndex()
操作将失败。
Consider the following 考虑下面的db.collection.createIndex()
operation:db.collection.createIndex()
操作:
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 }
,则索引创建操作将失败。
The following options are available for all index types unless otherwise specified:以下选项适用于所有索引类型,除非另有规定:
background |
boolean |
|
unique |
boolean |
|
name |
string |
|
partialFilterExpression |
document |
|
sparse |
boolean |
|
expireAfterSeconds |
integer | |
hidden |
boolean |
|
storageEngine |
document |
|
New in version 3.4.版本3.4中的新功能。
Warning
Collation is not supported in MongoDB 3.2 and earlier versions. MongoDB 3.2及更早版本不支持排序规则。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.在MongoDB 3.2和早期版本中,不要使用不受支持的排序规则选项创建索引,因为这将阻止升级到3.4,这将强制对索引选项进行更严格的验证。
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 | 1 .1 。 |
default_language |
string | 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 | -180.0 .-180.0 。 |
max |
number | 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:以下选项仅适用于通配符索引:
wildcardProjection |
document |
|
Changed in version 4.2.在版本4.2中更改。
For featureCompatibilityVersion 对于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. "4.2"
,db.collection.createIndex()
使用优化的生成过程,该过程在索引生成的开始和结束时获取并持有指定集合的独占锁。All subsequent operations on the collection must wait until 集合上的所有后续操作都必须等待db.collection.createIndex()
releases the exclusive lock. db.collection.createIndex()
释放独占锁。db.collection.createIndex()
allows interleaving read and write operations during the majority of the index build.db.collection.createIndex()
允许在索引生成的大部分过程中交替执行读写操作。
For featureCompatibilityVersion 对于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. "4.0"
,db.collection.createIndex()
使用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.createIndex()
, see Index Builds on Populated Collections.db.collection.createIndex()
锁定行为的更多信息,请参阅在填充的集合上构建索引。
If you call 如果为已经存在的索引调用db.collection.createIndex()
for an index that already exists, MongoDB does not recreate the index.db.collection.createIndex()
,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”或更早版本的MongoDB 2.6到MongoDB版本,如果现有文档的索引项超过最大索引键长度,MongoDB将不会在集合上创建索引。"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
.
Changed in version 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.createIndex()
in a transaction, the transaction must use read concern "local"
. db.collection.createIndex()
,该事务必须使用读关注点"local"
。If you specify a read concern level other than 如果指定的读取关注级别不是"local"
, the transaction fails."local"
,则事务失败。
The following example creates an ascending index on the field 以下示例在orderDate
.orderDate
字段上创建升序索引。
If the 如果keys文档指定了多个字段,则keys
document specifies more than one field, then createIndex()
creates a compound index.createIndex()
将创建一个复合索引。
The following example creates a compound index on the 以下示例在orderDate
field (in ascending order) and the zipcode
field (in descending order.)orderDate
字段(按升序)和zipcode
字段(按降序)上创建复合索引
Changed in version 4.4:在版本4.4中更改:Starting in MongoDB 4.4, compound indexes can include a single hashed field. 从MongoDB 4.4开始,复合索引可以包含一个哈希字段。Compound hashed indexes require featureCompatibilityVersion set to 复合哈希索引要求featureCompatibilityVersion设置为4.4
.4.4
。
The following example creates a compound index on the 以下示例在state
field (in ascending order) and the zipcode
field (hashed):state
字段(升序)和zipcode
字段(哈希)上创建复合索引:
The order of fields in a compound index is important for supporting 复合索引中字段的顺序对于支持使用索引的sort()
operations using the index.sort()
操作非常重要。
New in version 3.4.版本3.4中的新功能。
The following example creates an index named 下面的示例创建一个名为category_fr
. category_fr
的索引。The example creates the index with the collation that specifies the locale 该示例使用指定区域设置fr
and comparison strength 2
:fr
和比较强度2
的排序规则创建索引:
The following example creates a compound index named 下面的示例创建了一个名为date_category_fr
with a collation. date_category_fr
的复合索引,带有排序规则。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. 对于使用相同排序规则的索引键的查询或排序操作,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部署上设置功能兼容性版本。
_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
文档中组合包含和排除语句。
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 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. 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 为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. createIndex()
操作指定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"
, 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. 只有在携带数据的大多数投票成员“投票”提交索引构建后,primary才会将索引构建标记为就绪。For more information on index builds and the voting process, see Index Builds in Replicated Environments.有关索引生成和投票过程的更多信息,请参阅复制环境中的索引生成。
db.collection.getIndexes()
text
indexes.text
索引的详细信息。