Database Manual / Reference / mongosh Methods / Collections

db.collection.createIndexes() (mongosh method方法)

Definition定义

db.collection.createIndexes( [ keyPatterns ], options, commitQuorum )

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:MongoDB支持多种不同的索引类型,包括:

See index types for more information.有关更多信息,请参阅索引类型

Wildcard indexes support workloads where users query against custom fields or a large variety of fields in a collection:通配符索引支持用户查询自定义字段或集合中大量字段的工作负载:

  • You can create a wildcard index on a specific field and its subpaths or on all of the fields in a document.您可以在特定字段及其子路径上或文档中的所有字段上创建通配符索引。

    For details see, Wildcard Indexes.有关详细信息,请参阅通配符索引

optionsdocument文档Optional. 可选。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 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.副本集标记名

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Stable API

When using Stable API V1:当使用稳定API V1:

  • You cannot specify any of the following fields in the options document:您不能在options文档中指定以下任何字段:

    • background
    • bucketSize
    • sparse
    • storageEngine
  • You cannot create text indexes.您无法创建文本索引。
  • The above unsupported index types are ignored by the query planner in strict mode. 严格模式下,查询计划器会忽略上述不受支持的索引类型。For example, attempting to use a sparse index with cursor.hint() will result in the following BadValue error:例如,尝试将sparse索引与cursor.hint()一起使用将导致以下BadValue错误:

    planner returned error :: caused by :: hint provided does not
    correspond to an existing index

Options选项

The options document contains a set of options that control the creation of the indexes. Different index types can have additional options specific for that type.options文档包含一组控制索引创建的选项。不同的索引类型可以有特定于该类型的其他选项。

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. 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描述
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. The default value is false.指定true以创建唯一索引。默认值为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将通过连接索引字段的名称和排序顺序来生成索引名称。

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,$exists: true表达式,
  • $gt, $gte, $lt, $lte expressions,$gt$gte$lt$lte表达式,
  • $type expressions,表达式,
  • $and operator,运算符,
  • $or operator,运算符,
  • $in operator运算符

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. These indexes use less space but behave differently in some situations (particularly sorts). 如果为true,则索引仅引用具有指定字段的文档。这些索引使用较少的空间,但在某些情况下(特别是排序)表现不同。The default value is false. See Sparse Indexes for more information.默认值为false。有关更多信息,请参阅稀疏索引

The following index types are sparse by default and ignore this option:默认情况下,以下索引类型是稀疏的,忽略此选项:

For a compound index that includes 2dsphere index keys and keys for other types, only the 2dsphere index fields determine whether the index references a document.对于包含2dsphere索引键和其他类型键的复合索引,只有2dsphere索引字段决定索引是否引用文档。

Partial indexes have a superset of the sparse index functionality. Unless your application has a specific requirement, use partial indexes instead of sparse indexes.部分索引具有稀疏索引功能的超集。除非应用程序有特定要求,否则请使用部分索引而不是稀疏索引。

expireAfterSecondsinteger整数

Optional. 可选。Specifies a value, in seconds, as a time to live (TTL) to control how long MongoDB retains documents in this collection. 指定一个以秒为单位的生存时间(TTL)值,以控制MongoDB在此集合中保留文档的时间。This option only applies to TTL indexes. See Expire Data from Collections by Setting TTL for more information.此选项仅适用于TTL索引。有关更多信息,请参阅通过设置TTL从集合中过期数据

If you use TTL indexes created before MongoDB 5.0, or if you want to sync data created in MongDB 5.0 with a pre-5.0 installation, see Indexes Configured Using NaN to avoid misconfiguration issues.如果您使用MongoDB 5.0之前创建的TTL索引,或者如果您想将MongDB 5.0中创建的数据与5.0之前的安装同步,请参阅使用NaN配置的索引以避免配置错误问题。

The TTL index expireAfterSeconds value must be within 0 and 2147483647 inclusive.TTL索引expireAfterSeconds值必须在02147483647之间(包括021474647)。

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

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. For descriptions of the fields, see Collation Document.指定排序规则时,区域设置字段是必填的;所有其他排序字段都是可选的。有关字段的描述,请参阅排序规则文档

The following indexes only support simple binary comparison and do not support collation:以下索引仅支持简单的二进制比较,不支持排序规则

  • Text indexes索引
  • 2d indexes索引

Tip

To create a text or 2d index on a collection that has a non-simple collation, you must explicitly specify {collation: {locale: "simple"} } when creating the index.若要在具有非简单排序规则的集合上创建text2d索引,必须在创建索引时明确指定{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. Index with a collation strength of 1 is both diacritic- and case-insensitive.通过将排序规则strength指定为12,可以创建不区分大小写的索引。排序规则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.要使用索引进行字符串比较,操作还必须指定相同的排序规则。也就是说,如果操作指定了不同的排序规则,则具有排序规则的索引无法支持对索引字段执行字符串比较的操作。

Warning

Because indexes that are configured with collation use ICU collation keys to achieve sort order, collation-aware index keys may be larger than index keys for indexes without collation.因为配置了排序规则的索引使用ICU排序键来实现排序顺序,所以对于没有排序规则的指数,具有排序规则意识的索引键可能比索引键大。

A restaurants collection has the following documents:restaurants集合有以下文件:

db.restaurants.insertMany( [
{ _id: 1, category: "café", status: "Open" },
{ _id: 2, category: "cafe", status: "open" },
{ _id: 3, category: "cafE", status: "open" }
] )

The restaurants collection has an index on a string field category with the collation locale "fr".restaurants集合在排序规则为"fr"的字符串category类别上有一个索引。

db.restaurants.createIndex( { category: 1 }, { collation: { locale: "fr" } } )

The following query, which specifies the same collation as the index, can use the index:以下查询指定了与索引相同的排序规则,可以使用索引:

db.restaurants.find( { category: "cafe" } ).collation( { locale: "fr" } )

However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:但是,以下查询操作(默认情况下使用“简单”二进制排序器)不能使用索引:

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

db.restaurants.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.restaurants.find( { score: 5 } ).sort( { price: 1 } )
db.restaurants.find( { score: 5, price: { $gt: Decimal128( "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.restaurants.find( { score: 5, category: "cafe" } )

To confirm whether a query used an index, run the query with the explain() option.要确认查询是否使用了索引,请使用explain()选项运行查询。

Important

Matches against document keys, including embedded document keys, use simple binary comparison. This means that a query for a key like "type.café" will not match the key "type.cafe", regardless of the value you set for the strength parameter.与文档键(包括嵌入式文档键)的匹配使用简单的二进制比较。这意味着,无论您为strength参数设置了什么值,对类似“typecafé”的键的查询都不会与键“typecafe”匹配。

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. 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. 对于text索引,一种包含字段和权重对的文档。权重是一个从1到99999的整数,表示该字段相对于其他索引字段在分数方面的重要性。You can specify weights for some or all the indexed fields. See Assign Weights to Text Search Results on Self-Managed Deployments 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_languagestring字符串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 on Self-Managed Deployments for the available languages and Specify the Default Language for a Text Index on Self-Managed Deployments for more information and examples. The default value is english.有关可用语言,请参阅自我管理部署上的文本搜索语言,有关更多信息和示例,请参阅指定自我管理部署文本索引的默认语言。默认值为english
language_overridestring字符串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 Specify the Default Language for a Text Index on Self-Managed Deployments for an example.有关示例,请参阅指定自我管理部署上的文本索引的默认语言
textIndexVersioninteger整数

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

For available versions, see Text Index Versions on Self-Managed Deployments.有关可用版本,请参阅自我管理部署上的文本索引版本

Options for 2dsphere Indexes2dsphere索引选项

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

Parameter参数Type类型Description描述
2dsphereIndexVersioninteger整数

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

For the available versions, see 2dsphere Indexes.有关可用版本,请参阅2dsphere索引

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. The default value is 26.bits值的范围为1到32(包括1和32)。默认值为26

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

Options for wildcard Indexeswildcard索引选项

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

Parameter参数Type类型Description描述
wildcardProjectiondocument文档

Optional. 可选。Allows users to include or exclude specific field paths from a wildcard index.允许用户在通配符索引中包含或排除特定字段路径。

This option is only valid when you create an wildcard index on all document fields. You cannot specify the wildcardProjection option when you create a wildcard index on a specific field path and its subfields.此选项仅在为所有文档字段创建通配符索引时有效。在特定字段路径及其子字段上创建通配符索引时,不能指定wildcardProjection选项。

wildcardProjection works with specifications like:适用于以下规格:

{ "$**": 1 }
{ "userID":, "$**": 1 }

However, you can't define an index that includes the same field in the wildcard fields and the regular (non-wildcard) fields. To define the index correctly, use a wildcardProjection to exclude duplicated fields from the wildcard pattern.但是,您不能定义在通配符字段和常规(非通配符)字段中包含相同字段的索引。要正确定义索引,请使用wildcardProjection从通配符模式中排除重复字段。

wildcardProjection does not work with a specification like:不适用于以下规范:

 ``{ "path.to.field.$**" : 1 }``

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. To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document:默认情况下,通配符索引省略_id字段。要在通配符索引中包含_id字段,您必须在wildcardProjection文档中明确包含它:

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

All of the statements in the wildcardProjection document must be either inclusion or exclusion statements. You can also include the _id field with exclusion statements. This is the only exception to the rule.wildcardProjection文档中的所有语句都必须是包含或排除语句。您还可以在排除语句中包含_id字段。这是这条规则的唯一例外。

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行为

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. See Hidden Option.可以在不删除和重新创建索引的情况下更改隐藏选项。请参见隐藏选项

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.createIndexes()之前,使用db.collection.dropIndex()删除现有索引。

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隐藏选项

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

For example,例如,

Wildcard Indexes通配符索引

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

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

    All of the statements in the wildcardProjection document must be either inclusion or exclusion statements. You can also include the _id field with exclusion statements. This is the only exception to the rule.wildcardProjection文档中的所有语句都必须是包含或排除语句。您还可以在排除语句中包含_id字段。这是这条规则的唯一例外。

  • Wildcard indexes do not support:通配符索引不支持:

    Wildcard indexes are sparse indexes. They do not support queries when an indexed field does not exist. A wildcard index will index the document if the wildcard field has a null value.通配符索引是稀疏索引。当索引字段不存在时,它们不支持查询。如果通配符字段为null值,则通配符索引将对文档进行索引。

    Starting in MongoDB 7.0, wildcard indexes support ascending (1) and descending (-1) sort order. Earlier versions only supported ascending order.从MongoDB 7.0开始,通配符索引支持升序(1)和降序(-1)排序。早期版本仅支持升序。

To learn more, see:要了解更多信息,请参阅:

Transactions事务

You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.如果分布式事务不是跨分片写入事务,则可以在该事务内创建集合和索引。

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"以外的读取关注级别,则事务失败。

Index Builds指数构建

Changed in version 7.1.在版本7.1中的更改。

Starting in MongoDB 7.1, index builds are improved with faster error reporting and increased failure resilience. You can also set the minimum available disk space required for index builds using the new indexBuildMinAvailableDiskSpaceMB parameter, which stops index builds if disk space is too low.从MongoDB 7.1开始,索引构建得到了改进,错误报告更快,故障恢复能力更强。您还可以使用新的indexBuildMinAvailableDiskSpaceMB参数设置索引构建所需的最小可用磁盘空间,如果磁盘空间太低,该参数将停止索引构建。

The following table compares the index build behavior starting in MongoDB 7.1 with earlier versions.下表将MongoDB 7.1中开始的索引构建行为与早期版本进行了比较。

Behavior Starting in MongoDB 7.1Behavior in Earlier MongoDB Versions
Index errors found during the collection scan phase, except duplicate key errors, are returned immediately and then the index build stops. Earlier MongoDB versions return errors in the commit phase, which occurs near the end of the index build. 在集合扫描阶段发现的索引错误(重复键错误除外)会立即返回,然后索引构建停止。早期的MongoDB版本在提交阶段返回错误,该阶段发生在索引构建接近结束时。MongoDB 7.1 helps you to rapidly diagnose index errors. For example, if an incompatible index value format is found, the error is returned to you immediately.MongoDB 7.1可帮助您快速诊断索引错误。例如,如果发现不兼容的索引值格式,则会立即向您返回错误。Index build errors can take a long time to be returned compared to MongoDB 7.1 because the errors are returned near the end of the index build in the commit phase.与MongoDB 7.1相比,索引构建错误可能需要很长时间才能返回,因为错误是在提交阶段索引构建接近结束时返回的。
Increased resilience for your deployment. If an index build error occurs, a secondary member can request that the primary member stop an index build and the secondary member does not crash. 增强部署的弹性。如果发生索引构建错误,辅助成员可以请求成员停止索引构建,并且辅助成员不会崩溃。A request to stop an index build is not always possible: if a member has already voted to commit the index, then the secondary cannot request that the index build stop and the secondary crashes (similar to MongoDB 7.0 and earlier).停止索引构建的请求并不总是可能的:如果一个成员已经投票提交了索引,那么辅助服务器就不能请求停止索引构建,并且辅助服务器崩溃(类似于MongoDB 7.0及更早版本)。An index build error can cause a secondary member to crash.索引构建错误可能会导致辅助成员崩溃。
Improved disk space management for index builds. An index build may be automatically stopped if the available disk space is below the minimum specified in the indexBuildMinAvailableDiskSpaceMB parameter. 改进了索引构建的磁盘空间管理。如果可用磁盘空间低于indexBuildMinAvailableDiskSpaceMB参数中指定的最小值,则索引构建可能会自动停止。If a member has already voted to commit the index, then the index build is not stopped.如果成员已经投票提交索引,则索引构建不会停止。An index build is not stopped if there is insufficient available disk space.如果可用磁盘空间不足,索引构建也不会停止。

Example示例

Tip

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

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

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

db.restaurants.insertOne (
{
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. For details, see Collation and Index Use.对于使用相同排序规则的索引键的查询或排序操作,MongoDB可以使用索引。有关详细信息,请参阅排序规则和索引使用

Create a Wildcard Index创建通配符索引

For complete documentation on Wildcard Indexes, see Wildcard Indexes.有关通配符索引的完整文档,请参阅通配符索引

The following lists examples of wildcard index creation:以下列出了创建通配符索引的示例:

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

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:考虑一个集合products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:

db.products_catalog.insertMany( [
{
_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. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:考虑一个集合products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:

db.products_catalog.insertMany( [
{
_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. 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.使用此通配符索引,MongoDB对集合中每个文档的所有标量字段进行索引。如果给定字段是嵌套文档或数组,通配符索引将递归到文档/数组中,并对文档/数组的所有标量字段进行索引。

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. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:考虑一个集合products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:

db.products_catalog.insertMany( [
{
_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
}
}
)

The pattern "$**" includes all fields in the document. Use the wildcardProjection field to limit the index to the specified 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 wildcard index supports 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的更多信息,请参阅参数文档

Omit Specific Fields from Wildcard Index Coverage从通配符索引覆盖率中省略特定字段

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:考虑一个集合products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:

db.products_catalog.insertMany( [
{
_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" ]
}
}
] )

This example uses a wildcard index and a wildcardProjection document to index the scalar fields for each document in the collection. The wildcard index excludes the product_attributes.elements and product_attributes.resistance fields:此示例使用通配符索引和wildcardProjection文档对集合中每个文档的标量字段进行索引。通配符索引不包括product_attributes.elementsproduct_attributes.resistance一致性字段:

use inventory
db.products_catalog.createIndexes(
[ { "$**" : 1 } ],
{
"wildcardProjection" : {
"product_attributes.elements" : 0,
"product_attributes.resistance" : 0
}
}
)

The wildcard pattern "$**" includes all of the fields in the document. However, 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 index can support queries on any scalar field except fields that are 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+

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,才能在副本集成员之间同时启动索引构建。

Index builds on a replica set or sharded cluster build simultaneously across all data-bearing replica set members. 索引基于副本集构建,或在所有承载数据的副本集成员之间同时构建分片集群。For sharded clusters, the index build occurs only on shards containing data for the collection being indexed. The primary requires a minimum number of data-bearing voting members (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. 对于分片集群,索引构建仅发生在包含被索引集合的数据的分片上。初选需要最少数量的数据承载voting成员(即提交法定人数),包括其本身,在将索引标记为可供使用之前,必须完成构建。See Index Builds in Replicated Environments for more information.有关更多信息,请参阅复制环境中的索引构建

To set the commit quorum, use createIndexes() to specify the commitQuorum value.要设置提交合法人数,请使用createIndexes()指定commitQuorum值。

commitQuorum specifies how many data-bearing voting members, or which voting members, including the primary, must be prepared to commit the index build before the primary will execute the commit. The default commit quorum is votingMembers, which means all data-bearing members.指定在主节点执行提交之前,必须准备多少数据承载投票成员或哪些投票成员(包括主节点)来提交索引构建。默认的提交法定人数是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.有关索引构建和投票过程的更多信息,请参阅复制环境中的索引构建

Create Multiple Indexes创建多个索引

Create a cakeSales collection that contains cake sales in the states of California (CA) and Washington (WA):创建一个cakeSales集合,其中包含加利福尼亚州(CA)和华盛顿州(WA)的蛋糕销售:

db.cakeSales.insertMany( [
{ _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
state: "CA", price: 13, quantity: 120 },
{ _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
state: "WA", price: 14, quantity: 140 },
{ _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
state: "CA", price: 12, quantity: 145 },
{ _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
state: "WA", price: 13, quantity: 104 },
{ _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
state: "CA", price: 41, quantity: 162 },
{ _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
state: "WA", price: 43, quantity: 134 }
] )

The following example creates multiple indexes on the cakeSales collection:以下示例在cakeSales集合上创建了多个索引:

db.cakeSales.createIndexes( [
{ "type": 1 },
{ "orderDate": 1 },
{ "state": 1 },
{ "orderDate": 1, "state": -1 }
] )

The first three indexes are on single fields and in ascending order (1).前三个索引位于单个字段上,按升序排列(1)。

The last index is on orderDate in ascending order (1) and state in descending order (-1).最后一个索引按升序(1)排列在orderDate上,按降序(-1)排列在state上。

Additional Information附加信息

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