Docs HomeMongoDB Manual

db.collection.createIndex()

Definition定义

db.collection.createIndex(keys, options, commitQuorum)
Important

mongosh Method

This page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.

For the database command, see the createIndexes command.

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

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

mongo shell v4.4

Creates indexes on collections.在集合上创建索引。

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.要最大限度地减少在副本集和分片集群上构建索引的影响,请使用滚动索引构建过程,如在副本集上滚动索引构建中所述。

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

Parameter参数Type类型Description描述
keysdocumentA document that contains the 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. 对于字段的升序索引,请指定值1For descending index, specify a value of -1.对于递减索引,请指定值-1
An asterisk (*) is not a valid index name.星号(*)不是有效的索引名称。
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.有关详细信息,请参阅通配符索引
optionsdocumentOptional.可选的。A document that contains a set of options that controls the creation of the index. 包含一组选项的文档,这些选项控制索引的创建。See Options for details.有关详细信息,请参阅Options
commitQuoruminteger or stringOptional.可选的。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标记为就绪之前,必须报告成功生成索引的带有投票副本集成员(即commit quorum)(包括主索引)的最小数据数。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.复制副本集标记名称

New in version 4.4. 4.4版新增。

Options选项

The options document contains a set of options that controls the creation of the index. 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.createIndex() operation will fail.但是,如果指定了多个选项文档,则db.collection.createIndex()操作将失败。

Consider the following db.collection.createIndex() operation:考虑以下db.collection.createIndex()操作:

db.collection.createIndex(
{
"a": 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 },则索引创建操作将失败。

Options for All Index Types所有索引类型的选项

The following options are available for all index types unless otherwise specified:除非另有指定,否则以下选项可用于所有索引类型:

Parameter参数Type类型Description描述
uniquebooleanOptional.可选的。Creates a unique index so that the collection 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. 该选项不适用哈希索引
namestringOptional.可选的。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会通过连接索引字段的名称和排序顺序来生成索引名称。
partialFilterExpressiondocumentOptional.可选的。If specified, the index only references 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,运算符,
  • $or operator,运算符,
  • $in operator运算符
You can specify a partialFilterExpression option for all MongoDB index types. 您可以为所有MongoDB索引类型指定一个partialFilterExpression选项。
sparsebooleanOptional.可选的。If true, the index only references documents with the specified field. 如果为true,则索引仅引用具有指定字段的文档。These indexes use less space but behave differently in some situations (particularly sorts). 这些索引使用较少的空间,但在某些情况下(特别是排序)表现不同。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 key(s) along with keys of other types, only the 2dsphere index fields determine whether the index references a document. 对于包含2dsphere索引键和其他类型键的复合索引,只有2dsphere索引字段确定索引是否引用文档。
Tip
Partial indexes offer a superset of the functionality of sparse indexes. Unless your application has a specific requirement, use partial indexes instead of sparse indexes. 部分索引提供了稀疏索引功能的超集。除非您的应用程序有特定的要求,否则请使用部分索引而不是稀疏索引。
expireAfterSecondsintegerOptional.可选的。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. 此选项仅适用于TTL索引。See Expire Data from Collections by Setting TTL for more information.有关详细信息,请参阅通过设置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之间(包括02147463647)。
hiddenbooleanOptional.可选的。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.
New in version 4.4. 4.4版新增。
storageEnginedocumentOptional.可选的。Allows users to configure the storage engine on a per-index basis when creating an index.允许用户在创建索引时按每个索引配置存储引擎。
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描述
collationdocumentOptional.可选的。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.有关字段的说明,请参阅排序规则文档

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.若要在具有非简单排序规则的集合上创建text索引或2d索引,必须在创建索引时显式指定{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. 通过指定排序规则strength12,可以创建不区分大小写的索引。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:但是,以下查询操作(默认情况下使用"simple"二进制排序器)不能使用索引:

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有一个复合索引;索引是使用排序规则区域设置"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:以下操作使用“简单”二进制排序规则进行字符串比较,可以使用索引:

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描述
weightsdocumentOptional.可选的。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. 权重是一个从1到99999的整数,表示该字段相对于其他索引字段在分数方面的重要性。You can specify weights for some or all the indexed fields. See Assign Weights to Text Search Results 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. 对于text索引,确定停止词列表以及词干生成器和标记生成器规则的语言。See Text Search Languages for the available languages and Specify the Default Language for a 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. 对于文本索引,是集合文档中包含文档替代语言的字段的名称。The default value is language. 默认值为languageSee Specify the Default Language for a Text Index for an example.有关示例,请参阅指定文本索引的默认语言
textIndexVersionintegerOptional.可选的。The text index version number. text索引版本号。Users can use this option to override the default version number.用户可以使用此选项覆盖默认版本号。
For available versions, see Text Index Versions. 有关可用版本,请参阅文本索引版本

Options for 2dsphere Indexes2dsphere索引的选项

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

Parameter参数Type类型Description描述
2dsphereIndexVersionintegerOptional.可选的。The 2dsphere index version number. 2dsphere索引版本号。Users can use this option to override the default version number.用户可以使用此选项覆盖默认版本号。
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描述
bitsintegerOptional.可选的。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
minnumberOptional.可选的。For 2d indexes, the lower inclusive boundary for the longitude and latitude values. The default value is -180.0.对于2d索引,经度和纬度值的包含下限。默认值为-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 wildcard indexeswildcard索引选项

Wildcard indexes can use the wildcardProjection option.Wildcard索引可以使用wildcardProjection选项。

Parameter参数Type类型Description描述
wildcardProjectiondocumentOptional.可选的。Allows users to include or exclude specific field paths from a wildcard index.允许用户从wildcard索引中包括或排除特定字段路径。
This option is only valid when you create a wildcard index on all document fields. 只有在对所有文档字段创建wildcard索引时,此选项才有效。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. 默认情况下,通配符索引会省略_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
}
}
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. wildcardProjection文档中的所有语句都必须是包含语句或排除语句。您还可以将_id字段包含在排除语句中。This is the only exception to the rule. 这是该规则的唯一例外。

Behaviors行为

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

If you call db.collection.createIndex() for an index that already exists, MongoDB does not recreate the index.如果为已经存在的索引调用db.collection.createIndex(),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.除了collation选项之外,如果您使用一组索引选项创建索引,然后尝试使用不同的索引选项重新创建相同的索引,MongoDB将不会更改选项,也不会重新创建索引。

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

To change the other index options, drop the existing index with db.collection.dropIndex() before running db.collection.createIndex() with the new options.若要更改其他索引选项,请在使用新选项运行db.collection.createIndex()之前,先使用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隐藏选项

New in version 4.4. 4.4版新增。

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

For example,例如

Tip

See also: 另请参阅:

Hidden 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.createIndex() in a transaction, the transaction must use read concern "local". 若要在事务中使用db.collection.createIndex(),事务必须使用读取关注"local"If you specify a read concern level other than "local", the transaction fails.如果指定了"local"以外的读取关注级别,则事务将失败。

Examples实例

Create an Ascending Index on a Single Field在单个字段上创建升序索引

The following example creates an ascending index on the field orderDate.以下示例在字段orderDate上创建一个升序索引。

db.collection.createIndex( { orderDate: 1 } )

If the keys document specifies more than one field, then createIndex() creates a compound index.如果keys文档指定了多个字段,那么createIndex()将创建一个复合索引

Create an Index on a Multiple Fields在多个字段上创建索引

The following example creates a compound index on the orderDate field (in ascending order) and the zipcode field (in descending order.)以下示例在orderDate字段(按升序)和zipcode字段(按降序)上创建一个复合索引

db.collection.createIndex( { orderDate: 1, zipcode: -1 } )

Changed in version 4.4.4.4版更改。Starting in MongoDB 4.4, compound indexes can include a single hashed field. 从MongoDB 4.4开始,复合索引可以包括一个哈希字段。Compound hashed indexes require featureCompatibilityVersion set to 4.4.复合散列索引需要将featureCompatibilityVersion设置为4.4

The following example creates a compound index on the state field (in ascending order) and the zipcode field (hashed):以下示例在state字段(按升序)和zipcode字段(散列)上创建一个复合索引:

db.collection.createIndex( { "state" : 1, "zipcode" : "hashed" } )

The order of fields in a compound index is important for supporting sort() operations using the index.复合索引中字段的顺序对于支持使用索引的sort()操作非常重要。

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

The following example creates an index named category_fr. 以下示例创建一个名为category_fr的索引。The example creates the index with the collation that specifies the locale fr and comparison strength 2:该示例使用collation创建索引,该排序规则指定区域设置fr和比较强度2:

db.collection.createIndex(
{ category: 1 },
{ name: "category_fr", collation: { locale: "fr", strength: 2 } }
)

The following example creates a compound index named date_category_fr with a collation. The collation applies only to the index keys with string values.以下示例使用collation创建名为date_category_fr的复合索引。排序规则仅适用于具有字符串值的索引键。

db.collection.createIndex(
{ orderDate: 1, category: 1 },
{ name: "date_category_fr", collation: { locale: "fr", strength: 2 } }
)

The collation applies to the indexed keys whose values are string.排序规则适用于值为字符串的索引键。

For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. For details, see Collation and Index Use.对于使用相同排序规则的索引键的查询或排序操作,MongoDB可以使用索引。有关详细信息,请参阅排序规则和索引使用

Create a Wildcard Index创建通配符索引

  • 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
    }
    }

    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. wildcardProjection文档中的所有语句都必须是包含语句或排除语句。您还可以将_id字段包含在exclusion语句中。This is the only exception to the rule.这是该规则的唯一例外。

  • 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:要了解更多信息,请参阅:

For examples, see:有关示例,请参阅:

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.createIndex( { "product_attributes.$**" : 1 } )

With this wildcard index, MongoDB indexes all scalar values of 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.通过这个通配符索引,MongoDB为product_attributes的所有标量值建立索引。如果字段是嵌套文档或数组,则通配符索引将递归到文档/数组中,并对文档/数组的所有标量字段进行索引。

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.createIndex( { "$**" : 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.有关详细信息,请参阅参数文档

Include Specific Fields in Wildcard Index Coverage在通配符索引覆盖范围中包括特定字段

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.createIndex(
{ "$**" : 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 fields you specify. 使用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 it and indexes all scalar fields in the document or 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. 考虑一个集合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" ]
...
},
}

This example uses a wildcard index and a wildcardProjection document to index the scalar fields for each document in the collection.本例使用通配符索引和wildcardProjection文档为集合中的每个文档的标量字段编制索引。

The wildcard index excludes the product_attributes.elements and product_attributes.resistance fields:通配符索引不包括product_attributes.elementsproduct_attributes.resistance字段:

use inventory
db.products_catalog.createIndex(
{ "$**" : 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 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 Index 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,才能在副本集成员之间同时启动索引构建。

MongoDB 4.4 running featureCompatibilityVersion: "4.2" builds indexes on the primary before replicating the index build to secondaries.MongoDB 4.4运行featureCompatibilityVersion: "4.2"在主数据库上构建索引,然后将索引构建复制到辅助数据库。

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.有关详细信息,请参阅复制环境中的索引生成

To set the commit quorum, use createIndex() to specify the commitQuorum value.要设置提交仲裁,请使用createIndex()指定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", or a simple majority of data-bearing voting members:以下操作将创建一个提交法定人数"majority"或包含投票成员的简单多数数据的索引:

db.getSiblingDB("examples").invoices.createIndex(
{ "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附加信息

  • 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 Indexes索引 for details on creating text indexes.用于创建text索引。
  • geospatial Indexes索引 for geospatial queries.用于地理空间查询。
  • TTL Indexes索引 for expiration of data.用于数据过期。