db.collection.createIndexes()

On this page本页内容

Definition定义

db.collection.createIndexes( [ keyPatterns ], options, commitQuorum )
Important重要
mongosh Method

This is a mongosh method. This is not the documentation for Node.js or other programming language specific driver methods.

In most cases, mongosh methods work the same way as the legacy mongo shell methods. However, some legacy methods are unavailable in mongosh.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

For MongoDB API drivers, refer to the language specific MongoDB driver documentation.

Creates one or more indexes on a collection.在集合上创建一个或多个索引。

db.collection.createIndexes() takes the following parameters:采用以下参数:

Parameter参数Type类型Description描述
keyPatternsdocument

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. MongoDB支持多种不同的索引类型,包括text索引、geospatial索引和哈希索引。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:MongoDB 4.2通配符索引支持用户根据自定义字段或集合中的大量字段进行查询的工作负载:

  • 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. 特定于路径的通配符索引语法与wildcardProjection选项不兼容。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 mongodfeatureCompatibilityVersion must be 4.2 to create wildcard indexes. mongodfeatureCompatibilityVersion必须为4.2才能创建通配符索引。For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 5.0 Deployments.有关设置fCV的说明,请参阅在MongoDB 5.0部署上设置功能兼容性版本

For more information on creating wildcard indexes, see Wildcard Indexes.有关创建通配符索引的详细信息,请参阅通配符指数

optionsdocumentOptional. 可选。A document that contains a set of options that controls the creation of the indexes. 包含一组控制索引创建的选项的文档。See Options for details.有关详细信息,请参阅选项
commitQuoruminteger 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. 包含投票副本集成员(即提交仲裁)的数据的最小数量,包括主成员,在主成员将indexes标记为就绪之前,必须报告成功的索引构建A "voting" member is any replica set member where members[n].votes is greater than 0.“投票”成员是members[n].votes大于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 notvote 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 multiple 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. 当您为db.collection.createIndexes()指定选项时,这些选项将应用于所有指定的索引。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. 如果尝试使用不兼容的选项或太多的参数创建索引,db.collection.createIndexes()将返回错误。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描述
backgroundboolean

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. 对于功能兼容性版本(fcv)“4.0”,指定background:true将指示MongoDB在后台构建索引。Background builds do not block operations on the collection. 后台生成不会阻止对集合的操作。The default value is false.默认值为false
  • Changed in version 4.2.在版本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. 对于功能兼容性版本(fcv)"4.2",所有索引构建都使用优化的构建过程,该过程仅在构建过程的开始和结束时保持独占锁。The rest of the build process yields to interleaving read and write operations. 构建过程的其余部分将进行交错读写操作。MongoDB ignores the background option if specified.如果指定,MongoDB将忽略background选项。

uniqueboolean

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.该选项不适用于哈希索引。

namestring

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将通过连接索引字段的名称和排序顺序生成索引名称。

Note注意
Changed in MongoDB 4.2在MongoDB 4.2中更改

Starting in version 4.2, for featureCompatibilityVersion set to "4.2" or greater, MongoDB removes the Index Name Length limit of 127 byte maximum. 从4.2版开始,对于featureCompatibilityVersion设置为“4.2”或更高版本,MongoDB删除了最大127字节的索引名称长度限制。In previous versions or MongoDB versions with featureCompatibilityVersion (fCV) set to "4.0", index names must fall within the limit.featureCompatibilityVersion(fCV)设置为“4.0”的早期版本或MongoDB版本中,索引名称必须在限制范围内。

Options specified to db.collection.createIndexes() apply to all of the index specifications included in the key pattern array. 指定给db.collection.createIndexes()的选项适用于键模式数组中包含的所有索引规范。Since index names must be unique, you may only specify name if you are creating a single index using db.collection.createIndexes().由于索引名称必须是唯一的,所以只有在使用db.collection.createIndexes()创建单个索引时才能指定名称。

partialFilterExpressiondocument

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.您可以为所有MongoDB索引类型指定partialFilterExpression选项。

sparseboolean

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索引键和其他类型键的复合索引,只有2dsphee索引字段确定索引是否引用文档。

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或更高版本,则部分索引应优先于稀疏索引。

expireAfterSecondsintegerOptional. 可选。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索引。
hiddenboolean

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. 要使用隐藏选项,必须将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中新增

storageEnginedocument

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描述
collationdocument

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: {
   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.有关字段的说明,请参阅排序规则文档。

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的索引不区分音符和大小写。

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以及字符串字段category上有一个复合索引;索引是使用排序规则locale"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描述
weightsdocument

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

Starting in MongoDB 5.0, the weights option is only allowed for text indexes.从MongoDB 5.0开始,weights选项只允许用于文本索引。

default_languagestringOptional. 可选。For 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.默认值为english
language_overridestringOptional. 可选。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.有关示例,请参阅使用任何字段指定文档的语言
textIndexVersioninteger

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描述
2dsphereIndexVersioninteger

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描述
bitsinteger

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(含32)。The default value is 26.默认值为26

minnumberOptional. 可选。For 2d indexes, the lower inclusive boundary for the longitude and latitude values. 对于2d索引,经度和纬度值的包含边界下限。The default value is -180.0.默认值为-180.0
maxnumberOptional. 可选。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描述
bucketSizenumber

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。

Note注意
Removed in MongoDB 5.0在MongoDB 5.0中删除

MongoDB 5.0 removes the deprecated geoHaystack index and geoSearch command. MongoDB 5.0删除了弃用的geoHaystack索引和geoSearch命令。Use a 2d index with $geoNear or one of the supported geospatial query operators instead.改为使用带有$geoNear或支持的地理空间查询运算符之一的2d索引。

Upgrading your MongoDB instance to 5.0 and setting featureCompatibilityVersion to 5.0 will delete any pre-existing geoHaystack indexes.将MongoDB实例升级到5.0并将featureCompatibilityVersion设置为5.0将删除任何预先存在的geoHaystack索引。

Options for wildcard indexeswildcard索引选项

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

Parameter参数Type类型Description描述
wildcardProjectiondocument

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.索引不采用独占锁。

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排序规则选项

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 mongosh methods:要隐藏或取消隐藏现有索引,可以使用以下mongosh方法:

For example,例如

Tip提示
See also: 参阅:

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, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从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示例

Tip提示
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字段上的升序索引和类别字段上的升序索引。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 mongodfeatureCompatibilityVersion must be 4.2 to create wildcard indexes. mongodfeatureCompatibilityVersion必须为4.2才能创建通配符索引。For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 5.0 Deployments.有关设置fCV的说明,请参阅在MongoDB 5.0部署上设置功能兼容性版本

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. To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document. 通配符索引默认忽略_id字段。要在通配符索引中包含_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的完整文档,请参阅wildcard索引的选项

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_attributeselementsproduct_attributesresistance字段:

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的完整文档,请参阅wildcard索引的选项

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 exceptthose 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使用提交仲裁创建索引

Note注意
Requires featureCompatibilityVersion 4.4+需要功能兼容性版本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. 主索引需要最少数量的数据承载voting成员(即提交仲裁),包括其本身,必须在将索引标记为可使用之前完成构建。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参数,以设置包含投票成员(即提交仲裁)的数据的最小数量,包括主成员,必须在主成员将索引标记为就绪之前完成索引构建。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:有关索引的其他信息,请参阅:

  • The Indexes section of this manual for full documentation of indexes and indexing in MongoDB.本手册的索引部分提供了MongoDB中索引和索引的完整文档。
  • db.collection.getIndexes() to view the specifications of existing indexes for a collection.以查看集合的现有索引的规范。
  • Text Indexestext索引 for details on creating text indexes.有关创建text索引的详细信息。
  • Geospatial Indexes地理空间索引 for geospatial queries.用于地理空间查询。
  • TTL Indexes for expiration of data.用于数据过期。
←  db.collection.createIndex()db.collection.dataSize() →