db.collection.createIndexes()

On this page本页内容

Definition定义

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:采用以下参数:

Parameter参数Type类型Description描述
keyPatterns document

An array containing index specification documents. 包含索引规范文档的数组。Each document contains 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

MongoDB supports several different index types including text, geospatial, and hashed indexes. See index types for more information.

Changed in version 4.2.在版本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. 要在文档中的所有字段和子字段上创建通配符索引,请指定{ "$**" : 1 }作为索引键。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.还可以使用可选的wildcardProjection参数从索引中包括或排除特定字段及其子字段。

    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文档中明确包含它:

    {
      "wildcardProjection" : {
        "_id" : 1,
        "<field>" : 0|1
      }
    }

    With the exception of explicitly including _id field, you cannot combine inclusion and exclusion statements in the wildcardProjection 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 be 4.2 to create wildcard indexes. For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 4.4 Deployments.

For more information on creating wildcard indexes, see Wildcard Indexes.

options document Optional.可选。A document that contains a set of options that controls the creation of the indexes. 包含一组控制索引创建的选项的文档。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 where members[n].votes is greater than 0.

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 of 0, you cannot later modify the commit quorum using setIndexCommitQuorum.如果在提交仲裁为0的情况下启动索引生成,则以后无法使用setIndexCommitQuorum修改提交仲裁。
  • A replica set tag name.副本集标记名

New in version 4.4.版本4.4中的新功能。

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.要将在副本集和分片集群上构建索引的影响降至最低,请使用在副本集上构建滚动索引中所述的滚动索引构建过程。

Options选项

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()操作:

db.collection.createIndexes(
   [
     {
       "a": 1
     },
     {
       "b": 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.如果选项规范被拆分为以下多个文档:{ 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.有关更多信息,请参阅选项说明。

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.MongoDB 4.2中已弃用。

  • For feature compatibility version (fcv) "4.0", specifying background: true directs MongoDB to build the index in the background. Background builds do not block operations on the collection. The default value is false.
  • Changed in version 4.2.

    For feature compatibility version (fcv) "4.2", all index builds use an optimized build process that holds the exclusive lock only at the beginning and end of the build process. The rest of the build process yields to interleaving read and write operations. MongoDB ignores the background option if specified.

unique boolean

Optional.可选。Specifies that each index specified in the keyPatterns array is a unique index. 指定keyPatterns数组中指定的每个索引都是唯一的索引Unique indexes will not accept insertion or update of documents where the index key value matches an existing value in the index.如果索引键值与索引中的现有值匹配,则唯一索引将不接受插入或更新文档。

Specify true to create a unique index. 指定true以创建唯一索引。The default value is false.默认值为false

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.索引的名称。如果未指定,MongoDB将通过连接索引字段的名称和排序顺序来生成索引名。

Changed in MongoDB 4.2MongoDB 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.

Options specified to db.collection.createIndexes apply to all of the index specifications included in the key pattern array. Since index names must be unique, you may only specify name if you are creating a single index using db.collection.createIndexes.

partialFilterExpression document

Optional.可选。If specified, the indexes only reference documents that match the filter expression. 如果指定,索引仅引用与筛选器表达式匹配的文档。See Partial Indexes for more information.有关更多信息,请参阅部分索引

A filter expression can include:筛选器表达式可以包括:

  • equality expressions (i.e. field: value or using the $eq operator),等式表达式(即field: value或使用$eq运算符),
  • $exists: true expression,表示
  • $gt, $gte, $lt, $lte expressions,
  • $type expressions,
  • $and operator at the top-level only

You can specify a partialFilterExpression option for all MongoDB index types.

New in version 3.2.版本3.2中的新功能。

sparse boolean

Optional.可选。If true, the indexes only reference documents with the specified fields. 如果为true,则索引仅引用具有指定字段的文档。These indexes use less space but behave differently in some situations (particularly sorts). 这些索引使用更少的空间,但在某些情况下(尤其是排序)表现不同。The default value is false. 默认值为falseSee 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.对于包含2dsphere索引键和其他类型键的复合索引,只有2dsphere索引字段确定索引是否引用文档。

Changed in version 3.2:在3.2版中更改:Starting in MongoDB 3.2, MongoDB provides the option to create partial indexes. 从MongoDB 3.2开始,MongoDB提供了创建部分索引的选项。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.如果您使用的是MongoDB 3.2或更高版本,部分索引应该优先于稀疏索引。

expireAfterSeconds integer Optional.可选。Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. 以秒为单位指定一个值作为TTL,以控制MongoDB在此集合中保留文档的时间。See Expire Data from Collections by Setting TTL for more information on this functionality. 有关此功能的详细信息,请参阅通过设置TTL使集合中的数据过期This applies only to TTL indexes.这只适用于TTL索引。
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.默认值为false

To use the hidden option, you must have featureCompatibilityVersion set to 4.4 or greater. 要使用hidden选项,必须将featureCompatibilityVersion设置为4.4或更高。However, once hidden, the index remains hidden even with featureCompatibilityVersion set to 4.2 on MongoDB 4.4 binaries.然而,一旦隐藏,即使在MongoDB 4.4二进制文件上featureCompatibilityVersion设置为4.2,索引仍然隐藏。

New in version 4.4.版本4.4中的新功能。

storageEngine document

Optional.可选。Allows users to configure the storage engine for the created indexes.允许用户为创建的索引配置存储引擎。

The storageEngine option should take the following form:storageEngine选项应采用以下形式:

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.创建索引时指定的存储引擎配置选项将在复制期间验证并记录到oplog,以支持使用不同存储引擎的成员的副本集。

Option for Collation排序选项

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:如果已在集合级别指定排序规则,则:

  • If you do not specify a collation when creating the index, MongoDB creates the index with the collection’s default collation.如果在创建索引时未指定排序规则,MongoDB将使用集合的默认排序规则创建索引。
  • If you do specify a collation when creating the index, MongoDB creates the index with the specified collation.如果在创建索引时指定了排序规则,MongoDB将使用指定的排序规则创建索引。

The collation option has the following syntax:collation选项语法如下所示:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关这些字段的描述,请参阅排序规则文档

New in version 3.4.版本3.4中的新功能。

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.要在具有非简单排序规则的集合上创建text2dgeoHaystack索引,必须在创建索引时显式指定{collation: {locale: "simple"} }

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.如果在创建索引时未指定排序规则,MongoDB将使用集合的默认排序规则创建索引。
  • If you do specify a collation when creating the index, MongoDB creates the index with the specified collation.如果在创建索引时指定了排序规则,MongoDB将使用指定的排序规则创建索引。

Tip

By specifying a collation strength of 1 or 2, you can create a case-insensitive index. 通过将排序规则strength指定为12,可以创建不区分大小写的索引。Index with a collation strength of 1 is both diacritic- and case-insensitive.排序规则strength1的索引既不区分重音,也不区分大小写。

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上有一个索引。

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:例如,集合myColl在数字字段scoreprice以及字符串字段类别上有一个复合索引;索引是使用排序规则区域设置"fr"创建的,用于字符串比较:

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:以下使用"simple"二进制排序规则进行字符串比较的操作可以使用索引:

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:以下操作使用"simple"二进制排序规则对索引category字段进行字符串比较,可以使用索引只完成查询的score: 5部分:

db.myColl.find( { score: 5, category: "cafe" } )

Options for text Indexestext索引选项

The following options are available for text indexes only:以下选项仅适用于text索引:

Parameter参数Type类型Description描述
weights document Optional.可选。For text indexes, a document that contains field and weight pairs. 对于text索引,包含字段和权重对的文档。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. 权重是一个介于1到99999之间的整数,表示该字段相对于其他索引字段在分数方面的重要性。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.默认值为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. 对于text索引,确定停止词列表以及词干分析器和标记器规则的语言。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.默认值为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. 对于text索引,集合文档中包含文档重写语言的字段的名称。The default value is language. 默认值是languageSee Use any Field to Specify the Language for a Document for an example.有关示例,请参阅使用任何字段指定文档的语言
textIndexVersion integer

Optional.可选。The text index version number. text索引版本号。Users can use this option to override the default version number.用户可以使用此选项覆盖默认版本号。

For available versions, see Versions.有关可用版本,请参阅版本

Options for 2dsphere Indexes2dsphere索引的选项

The following option is available for 2dsphere indexes only:以下选项仅适用于2dsphere索引:

Parameter参数Type类型Description描述
2dsphereIndexVersion integer

Optional.可选。The 2dsphere index version number. 2dsphere索引版本号。Users can use this option to override the default version number.用户可以使用此选项覆盖默认版本号。

For the available versions, see Versions.有关可用版本,请参阅版本

Options for 2d Indexes2d索引的选项

The following options are available for 2d indexes only:以下选项仅适用于2d索引:

Parameter参数Type类型Description描述
bits integer

Optional.可选。For 2d indexes, the number of precision of the stored geohash value of the location data.对于2d索引,存储的位置数据的geohash值的精度数。

The bits value ranges from 1 to 32 inclusive. bits值的范围为1到32(含1到32)。The default value is 26.默认值为26

min number Optional.可选。For 2d indexes, the lower inclusive boundary for the longitude and latitude values. 对于2d索引,指经度和纬度值的下包容边界。The default value is -180.0.默认值为-180.0
max number Optional.可选。For 2d indexes, the upper inclusive boundary for the longitude and latitude values. 对于2d索引,是经度和纬度值的上包容边界。The default value is 180.0.默认值为180.0

Options for geoHaystack IndexesgeoHaystack索引选项

The following option is available for geoHaystack indexes only:以下选项仅适用于geoHaystack索引:

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.对于geoHaystack索引,指定将位置值分组的单元数;也就是说,在同一个桶中,将指定数量单位内的位置值相互分组。

The value must be greater than 0.该值必须大于0。

Options for wildcard indexeswildcard索引选项

The following option is available for wildcard indexes only:以下选项仅适用于wildcard索引:

Parameter参数Type类型Description描述
wildcardProjection document

Optional.可选。Allows users to include or exclude specific field paths from the wildcard index. 允许用户从通配符索引中包括或排除特定字段路径。This option is only valid if creating a wildcard index.此选项仅在创建通配符索引时有效。

The wildcardProjection option takes the following form:wildcardProjection选项采用以下形式:

wildcardProjection: {
  "path.to.field.a" : <value>,
  "path.to.field.b" : <value>
}

The <value> can be either of the following:<value>可以是以下任一项:

  • 1 or true to include the field in the wildcard index.1true,将该字段包括在通配符索引中。
  • 0 or false to exclude the field from the wildcard index.0false将该字段从通配符索引中排除。

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文档中明确包含它:

{
  "wildcardProjection" : {
    "_id" : 1,
    "<field>" : 0|1
  }
}

With the exception of explicitly including _id field, you cannot combine inclusion and exclusion statements in the wildcardProjection document.除了显式包含_id字段外,不能在wildcardProjection文档中组合包含和排除语句。

Options specified to db.collection.createIndexes apply to all of the index specifications included in the key pattern array. db.collection.createIndexes指定的选项适用于键模式数组中包含的所有索引规范。Specify wildcardProjection only if you are creating a single wildcard index using db.collection.createIndexes.仅当使用db.collection.createIndexes创建单个通配符索引时,才指定wildcardProjection

Behaviors行为

Concurrency并发性

Changed in version 4.2.在版本4.2中更改。

For 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. 对于featureCompatibilityVersion "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 "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. 对于featureCompatibilityVersion "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()锁定行为的更多信息,请参阅基于填充集合的索引构建

Recreating an Existing Index重新创建现有索引

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不会重新创建现有的一个或多个索引。

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.除了排序规则选项之外,如果使用一组索引选项创建索引,然后尝试使用不同的索引选项重新创建相同的索引,MongoDB将不会更改选项,也不会重新创建索引。

The hidden option can be changed without dropping and recreating the index. 可以在不删除和重新创建索引的情况下更改hidden选项。See Hidden Option.请参见hidden选项

To change the other index options, drop the existing index with db.collection.dropIndex() before running db.collection.createIndexes() with the new options.要更改其他索引选项,请先使用db.collection.dropIndex()删除现有索引,然后再使用新选项运行db.collection.createIndexes()

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.要创建具有相同键模式但不同排序规则的索引,必须提供唯一的索引名。

Hidden Option隐藏选项

New in version 4.4.版本4.4中的新功能。

Note

To hide an index, you must have featureCompatibilityVersion set to 4.4 or greater. 要隐藏索引,必须将featureCompatibilityVersion设置为4.4或更高。However, once hidden, the index remains hidden even with featureCompatibilityVersion set to 4.2 on MongoDB 4.4 binaries.然而,一旦隐藏,即使在MongoDB 4.4二进制文件上featureCompatibilityVersion设置为4.2,索引仍然隐藏。

To hide or unhide existing indexes, you can use the following mongo shell methods:要隐藏或取消隐藏现有索引,可以使用以下mongo shell方法:

For example,例如

See also参阅

Hidden Indexes

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.对于featureCompatibilityVersion(fCV)设置为"4.0"或更早版本的MongoDB 2.6到MongoDB版本,如果现有文档的索引项超过最大索引键长度,MongoDB将不会在集合上创建索引。

Wildcard Indexes

New in version 4.2.版本4.2中的新功能。

For examples of wildcard index creation, see Create a Wildcard Index. 有关创建通配符索引的示例,请参阅创建通配符索引For complete documentation on Wildcard Indexes, see Wildcard Indexes.有关通配符索引的完整文档,请参阅通配符索引

Transactions事务

Changed in version 4.4.在版本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.功能兼容版本(fcv)"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",则事务失败。

Example示例

See also参阅

db.collection.createIndex() for examples of various index specifications.有关各种索引规范的示例。

Create Indexes Without Options创建没有选项的索引

Consider a restaurants collection containing documents that resemble the following:考虑一个包含类似以下文件的restaurants集合:

{
   location: {
      type: "Point",
      coordinates: [-73.856077, 40.848447]
   },
   name: "Morris Park Bake Shop",
   cuisine: "Cafe",
   borough: "Bronx",
}

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索引。

db.restaurants.createIndexes([{"borough": 1}, {"location": "2dsphere"}])

Create Indexes with Collation Specified使用指定的排序规则创建索引

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

db.products.createIndexes( [ { "manufacturer": 1}, { "category": 1 } ],
   { collation: { locale: "fr", strength: 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.有关详细信息,请参阅排序规则和索引使用

Create a Wildcard Index创建一个通配符索引

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:下面列出了创建通配符索引的示例:

Create a Wildcard Index on a Single Field Path在单个字段路径上创建通配符索引

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字段可以包含任意嵌套字段,包括嵌入的文档和数组:

{
  "_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:以下操作在product_attributes字段上创建通配符索引:

use inventory
db.products_catalog.createIndexes(
  [ { "product_attributes.$**" : 1 } ]
)

With this wildcard index, MongoDB indexes all scalar values of product_attributes. 通过这个通配符索引,MongoDB对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或其中一个嵌套字段的任意单字段查询:

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" } } )

Note

The path-specific wildcard index syntax is incompatible with the wildcardProjection option. 路径特定的通配符索引语法与wildcardProjection选项不兼容。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. 考虑一个集合products_catalog,其中文档可以包含一个product_attributes字段。The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes字段可以包含任意嵌套字段,包括嵌入的文档和数组:

{
  "_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):以下操作在所有标量字段(不包括_id字段)上创建通配符索引:

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 1 } ]
)

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:创建的索引可以支持对集合中文档中任意字段的查询:

db.products_catalog.find( { "product_price" : { $lt : 25 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )

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.有关更多信息,请参阅参数文档

Create a Wildcard Index on Multiple Specific Field Paths在多个特定字段路径上创建通配符索引

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字段可以包含任意嵌套字段,包括嵌入的文档和数组:

{
  "_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.以下操作创建通配符索引,并使用wildcardProjection选项仅包括索引中product_attributes.elementsproduct_attributes.resistance字段的标量值。

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 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. 虽然键模式"$**"涵盖文档中的所有字段,但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中包含的任何标量字段的查询:

db.products_catalog.find( { "product_attributes.elements" : { $eq: "Water" } } )
db.products_catalog.find( { "product_attributes.resistance" : "Bludgeoning" } )

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的更多信息,请参阅参数文档

Create a Wildcard Index that Excludes Multiple Specific Field Paths创建排除多个特定字段路径的通配符索引

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字段可以包含任意嵌套字段,包括嵌入的文档和数组:

{
  "_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:以下操作创建通配符索引,并使用wildcardProjection文档为集合中每个文档的所有标量字段编制索引,不包括product_attributes.elements字段和product_attributes.resistance字段:

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 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. 虽然键模式"$**"涵盖文档中的所有字段,但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排除的字段除外:

db.products_catalog.find( { "product_attributes.maxSpeed" : { $gt: 25 } } )
db.products_catalog.find( { "product_attributes.superStrength" : true } )

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的更多信息,请参阅参数文档

Create Indexes 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.副本集或分片集群中的每个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 voting members (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. primary需要最少数量的数据承载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, or all data-bearing voting replica set members.默认提交仲裁为votingMembers,或所有数据承载投票副本集成员。

The following operation creates an index with a commit quorum of "majority":以下操作将创建提交仲裁为"majority"的索引:

db.getSiblingDB("examples").invoices.createIndexes(
  { "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. 只有在携带数据的大多数投票成员“投票”提交索引构建后,primary才会将索引构建标记为就绪。For more information on index builds and the voting process, see Index Builds in Replicated Environments.有关索引生成和投票过程的更多信息,请参阅复制环境中的索引生成

Additional Information其他信息

For additional information about indexes, refer to:有关索引的更多信息,请参阅: