createIndexes

On this page本页内容

Definition定义

createIndexes

Builds one or more indexes on a collection.在集合上生成一个或多个索引。

The createIndexes command takes the following form:createIndexes命令采用以下形式:

db.runCommand(
  {
    createIndexes: <collection>,
    indexes: [
        {
            key: {
                <key-value_pair>,
                <key-value_pair>,
                ...
            },
            name: <index_name>,
            <option1>,
            <option2>,
            ...
        },
        { ... },
        { ... }
    ],
    writeConcern: { <write concern> },
    commitQuorum: <int|string>,
    comment: <any>
  }
)

The createIndexes command takes the following fields:createIndexes命令接受以下字段:

Field字段Type类型Description描述
createIndexesstringThe collection for which to create indexes.要为其创建索引的集合。
indexesarraySpecifies the indexes to create. Each document in the array specifies a separate index. 指定要创建的索引。数组中的每个文档都指定一个单独的索引。
writeConcerndocumentOptional. 可选。A document expressing the write concern. 表示写入关注的文档。Omit to use the default write concern.忽略使用默认的写入关注。
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. 包含投票副本集成员(即提交仲裁)的数据承载的最小数量,包括主成员,必须在主成员将索引标记为就绪之前报告成功的索引生成A "voting" member is any replica set member where members[n].votes is greater than 0.“投票”成员是members[n].votes大于0的任何复制集成员。

Starting in MongoDB v5.0 you can resume some interupted index builds when the commit quorum is set to "votingMembers".从MongoDB v5.0开始,当提交仲裁设置为"votingMembers"时,您可以恢复一些中断的索引构建

The "votingMembers" commit quorum cannot be used if any voting replica set node is configured with members[n].buildIndexes set to false. 如果任何投票副本集节点的members[n].buildIndexes设置为false,则无法使用"votingMembers"提交仲裁。Either configure all nodes with members[n].buildIndexes set to true or select a commit quorum that requires fewer votes.配置members[n].buildIndexes设置为true的所有节点,或选择需要更少投票的提交仲裁。

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中新增

commentany

Optional. 可选。A user-provided comment to attach to this command. 用户提供了附加到此命令的注释。Once set, this comment appears alongside records of this command in the following locations:设置后,此注释将与此命令的记录一起显示在以下位置:

A comment can be any valid BSON type(string, integer, object, array, etc).注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

New in version 4.4.在版本4.4中新增

Each document in the indexes array can take the following fields:indexes数组中的每个文档都可以采用以下字段:

Field字段Type类型Description描述
keydocument

Specifies the index's fields. 指定索引的字段。For each field, specify a key-value pair in which the key is the name of the field to index and the value is either the index direction or index type. 对于每个字段,指定一个键值对,其中键是要索引的字段的名称,值是索引方向或索引类型If specifying direction, specify 1 for ascending or -1 for descending.如果指定方向,请指定1表示升序或-1表示降序。

MongoDB supports several different index types including text, geospatial, and hashed indexes. MongoDB支持多种不同的索引类型,包括文本索引、地理空间索引和哈希索引。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. mongod-featureCompatibilityVersion必须为4.2才能创建通配符索引。For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 5.0 Deployments.有关设置fCV的说明,请参阅在MongoDB 5.0 Deployments上设置功能兼容性版本

For examples of wildcard index creation, see Create a Wildcard Index.有关创建通配符索引的示例,请参阅创建通配符索引

namestringA name that uniquely identifies the index.唯一标识索引的名称。
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. 可选。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.该选项不适用于哈希索引。

partialFilterExpressiondocument

Optional. 可选。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 at the top-level only仅位于顶层的$and运算符

You can specify a partialFilterExpression option for all MongoDB index types.您可以为所有MongoDB索引类型指定partialFilterExpression选项。

sparseboolean

Optional. 可选。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. 默认值为falseSee Sparse Indexes for more information.有关详细信息,请参阅稀疏索引。

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

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

Changed in version 3.2.在版本3.2中更改

Starting in MongoDB 3.2, MongoDB provides the option to create partial indexes. 从MongoDB 3.2开始,MongoDB提供创建部分索引的选项。Partial indexes offer a superset of the functionality of sparse indexes. 部分索引提供了稀疏索引功能的超集。If you are using MongoDB 3.2 or later, partial indexes should be preferred over sparse indexes.如果您使用MongoDB 3.2或更高版本,则应首选部分索引而非稀疏索引。

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 query plan selection.隐藏索引不会作为查询计划选择的一部分进行计算。

Default is false.默认值为false

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

New in version 4.4.在版本4.4中新增

storageEnginedocument

Optional. 可选。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中,以支持具有使用不同存储引擎的成员的副本集。

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 Control Search Results with Weights to adjust the scores. 请参见使用权重控制搜索结果以调整分数。The default value is 1. 默认值为1
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. Users can use this option to override the default version number.text索引版本号。用户可以使用此选项覆盖默认版本号。

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

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.有关可用版本,请参阅版本

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(包括1和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
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。

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

wildcardProjectiondocument

Optional.可选。

Allows users to include or exclude specific field paths from a wildcard index using the { "$**" : 1} key pattern. 允许用户使用{ "$**" : 1}键模式从通配符索引中包含或排除特定字段路径。This option is only valid if creating a wildcard index on all document fields. 只有在所有文档字段上创建通配符索引时,此选项才有效。You cannot specify this option if creating a wildcard index on a specific field path and its subfields, e.g. { "path.to.field.$**" : 1 }如果在特定字段路径及其子字段上创建通配符索引,则不能指定此选项,例如{ "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
  }
}

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

mongosh provides the methods db.collection.createIndex() and db.collection.createIndexes() as wrappers for the createIndexes command.提供了方法db.collection.createIndex()db.collection.createIndexes()作为createIndexes命令的包装器。

Considerations注意事项

Changed in version 3.2.在版本3.2中更改

MongoDB disallows the creation of version 0 indexes. MongoDB不允许创建版本0索引。To upgrade existing version 0 indexes, see Version 0 Indexes.要升级现有的版本0索引,请参阅版本0索引

Index Names索引名称

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版本中,索引名称必须在限制范围内。

Starting in version 4.2, the createIndexes command and mongosh helpers db.collection.createIndex() and db.collection.createIndexes() report an error if you create an index with one name, and then try to create the same index again but with another name.从4.2版开始,如果您使用一个名称创建索引,然后尝试使用另一个名称再次创建相同的索引,则createIndexes命令和mongosh助手db.collection.createIndex()db.collection.createIndexes()会报告错误。

{
   "ok" : 0,
   "errmsg" : "Index with name: x_1 already exists with a different name",
   "code" : 85,
   "codeName" : "IndexOptionsConflict"
}

In previous versions, MongoDB did not create the index again, but would return a response object with ok value of 1 and a note that implied that the index was not recreated. 在以前的版本中,MongoDB不会再次创建索引,但会返回一个ok值为1的响应对象,以及一个表示未重新创建索引的注释。For Example:例如:

{
   "numIndexesBefore" : 2,
   "numIndexesAfter" : 2,
   "note" : "all indexes already exist",
   "ok" : 1
}

Replica Sets and Sharded Clusters副本集和共享群集

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

To start an index build with a non-default commit quorum, specify the commitQuorum.要使用非默认提交仲裁启动索引生成,请指定commitQuorum

MongoDB 4.4 adds the setIndexCommitQuorum command for modifying the commit quorum of an in-progress index build.MongoDB 4.4添加了setIndexCommitQuorum命令,用于修改正在进行的索引构建的提交仲裁。

In MongoDB 4.2 and earlier, index builds on a replica set or sharded cluster build on the primary first before replicating to the secondaries. 在MongoDB 4.2和更早版本中,索引构建在副本集或分片集群上,首先构建在主集群上,然后再复制到辅助集群。See Index Builds In Replicated Environments (4.2) for the MongoDB 4.2 index build behavior.有关MongoDB 4.2索引构建行为,请参阅复制环境中的索引构建(4.2)

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

Collation and Index Types排序规则和索引类型

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

Stable API

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

  • You cannot specify any of the following fields in the indexes array:不能在indexes数组中指定以下任何字段:

    • background
    • bucketSize
    • sparse
    • storageEngine
  • You cannot create geoHaystack or text indexes.无法创建geoHaystacktext索引。

Behavior行为

Concurrency并发性

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

For featureCompatibilityVersion "4.2", 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"createIndexes使用一个优化的构建过程,该过程在索引构建的开始和结束时获取并保持对指定集合的独占锁。All subsequent operations on the collection must wait until createIndexes releases the exclusive lock. 集合上的所有后续操作必须等待createIndexes释放独占锁。createIndexes allows interleaving read and write operations during the majority of the index build.createIndexes允许在大多数索引构建过程中交错读取和写入操作。

For featureCompatibilityVersion "4.0", 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"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 createIndexes, see Index Builds on Populated Collections.有关createIndexes的锁定行为的更多信息,请参阅在填充集合上生成索引

Memory Usage Limit内存使用限制

Changed in version 3.4.在版本3.4中更改

createIndexes supports building one or more indexes on a collection. 支持在集合上构建一个或多个索引。createIndexes uses a combination of memory and temporary files on disk to complete index builds. 使用磁盘上的内存和临时文件的组合来完成索引构建。The default limit on memory usage for createIndexes is 200 megabytes (for versions 4.2.3 and later) and 500 (for versions 4.2.2 and earlier), shared between all indexes built using a single createIndexes command. createIndexes的默认内存使用限制为200兆字节(对于4.2.3及更高版本)和500兆字节(针对4.2.2及更低版本),在使用单个createIndexes命令构建的所有索引之间共享。Once the memory limit is reached, createIndexes uses temporary disk files in a subdirectory named _tmp within the --dbpath directory to complete the build. 一旦达到内存限制,createIndexes将使用--dbpath目录中名为_tmp的子目录中的临时磁盘文件来完成构建。You can override the memory limit by setting the maxIndexBuildMemoryUsageMegabytes server parameter. 您可以通过设置maxIndexBuildMemoryUsageMegabytes服务器参数来覆盖内存限制。Setting a higher memory limit may result in faster completion of index builds. 设置更高的内存限制可能会更快地完成索引构建。However, setting this limit too high relative to the unused RAM on your system can result in memory exhaustion and server shutdown.但是,相对于系统上未使用的RAM,将此限制设置得太高可能会导致内存耗尽和服务器关闭。

Index Options索引选项

Non-Hidden Option非隐藏选项

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

Changing Index Options更改索引选项

Collation options on an existing index can be updated. 可以更新现有索引上的排序规则选项。To change other index options, drop the existing index with db.collection.dropIndex() then run createIndexes with the new options.要更改其他索引选项,请使用db.collection.dropIndex()删除现有索引,然后使用新选项运行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.要创建具有相同键模式但排序规则不同的索引,必须提供唯一的索引名称。

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

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创建的,用于字符串比较:

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

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 change the hidden option for existing indexes, you can use the following mongosh methods:要更改现有索引的hidden选项,可以使用以下mongosh方法:

For Example,例如,

Tip提示
See also: 参阅:

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 createIndexes in a transaction, the transaction must use read concern "local". 要在事务中使用createIndexes,事务必须使用读取关注点"local"If you specify a read concern level other than "local", the transaction fails.如果指定的读取关注级别不是"local",则事务将失败。

Example示例

The following command builds two indexes on the inventory collection of the products database:以下命令在products数据库的inventory集合上构建两个索引:

db.getSiblingDB("products").runCommand(
  {
    createIndexes: "inventory",
    indexes: [
        {
            key: {
                item: 1,
                manufacturer: 1,
                model: 1
            },
            name: "item_manufacturer_model",
            unique: true
        },
        {
            key: {
                item: 1,
                supplier: 1,
                model: 1
            },
            name: "item_supplier_model",
            unique: true
        }
    ],
    writeConcern: { w: "majority" }
  }
)

When the indexes successfully finish building, MongoDB returns a results document that includes a status of "ok" : 1.当索引成功构建完成后,MongoDB返回一个结果文档,该文档的状态为"ok" : 1

Create a Wildcard Index创建通配符索引

New in version 4.2.在版本4.2中新增 The mongodfeatureCompatibilityVersion must be 4.2 to create wildcard indexes. mongod-featureCompatibilityVersion必须为4.2才能创建通配符索引。For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 5.0 Deployments.有关设置fCV的说明,请参阅在MongoDB 5.0 Deployments上设置功能兼容性版本

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.runCommand(
  {
    createIndexes: "products_catalog",
    indexes: [
      {
        key: { "product_attributes.$**" : 1 },
        name: "wildcardIndex"
      }
    ]
  }
)

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.runCommand(
  {
    createIndexes: "products_catalog",
    indexes: [
      {
        key: { "$**" : 1 },
        name: "wildcardIndex"
      }
    ]
  }
)

With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. 使用此通配符索引,MongoDB为集合中每个文档的所有标量字段编制索引。If a given field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.如果给定字段是嵌套的文档或数组,则通配符索引将递归到文档/数组中,并对文档/数组的所有标量字段进行索引。

The created index can support queries on any arbitrary field within documents in the collection:创建的索引可以支持对集合中文档中任意字段的查询:

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

Wildcard indexes omit the _id field by default. 默认情况下,通配符索引忽略_id字段。To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document. 要在通配符索引中包含_id字段,必须在wildcardProjection文档中显式包含它。See parameter documentation for more information.有关详细信息,请参阅参数文档

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

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

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index and uses the wildcardProjection option to include only scalar values of the product_attributes.elements and product_attributes.resistance fields in the index.以下操作创建通配符索引,并使用wildcardProjection选项在索引中仅包含product_attributes.elementsproduct_attributes.resistance字段的标量值。

use inventory
db.runCommand(
  {
    createIndexes: "products_catalog",
    indexes: [
      {
        key: { "$**" : 1 },
        "wildcardProjection" : {
          "product_attributes.elements" : 1,
          "product_attributes.resistance" : 1
        },
        name: "wildcardIndex"
      }
    ]
  }
)

While the key pattern "$**" covers all fields in the document, the wildcardProjection field limits the index to only the included fields and their nested fields.虽然键模式"$**"覆盖了文档中的所有字段,但wildcardProjection字段将索引限制为仅包含的字段及其嵌套字段。

If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.如果字段是嵌套的文档或数组,则通配符索引将递归到文档/数组中,并为文档/数组的所有标量字段编制索引。

The created index can support queries on any scalar field included in the wildcardProjection:创建的索引可以支持对wildcardProjection中包含的任何标量字段的查询:

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

Wildcard indexes do not support mixing inclusion and exclusion statements in the wildcardProjection document except when explicitly including the _id field. 通配符索引不支持在wildcardProjection文档中混合包含和排除语句,除非明确包含_id字段。For more information on wildcardProjection, see the parameter documentation.有关wildcardProjection的更多信息,请参阅参数文档

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

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

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index and uses the wildcardProjection document to index all scalar fields for each document in the collection, excluding the product_attributes.elements and product_attributes.resistance fields:以下操作创建通配符索引,并使用wildcardProjection文档为集合中每个文档的所有标量字段编制索引,不包括product_attributes.elementsproduct_attributes.resistance字段:

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

While the key pattern "$**" covers all fields in the document, the wildcardProjection field excludes the specified fields from the index.虽然键模式"$**"覆盖文档中的所有字段,但wildcardProjection字段将索引中的指定字段排除在外。

If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.如果字段是嵌套的文档或数组,则通配符索引将递归到文档/数组中,并为文档/数组的所有标量字段编制索引。

The created index can support queries on any scalar field except those excluded by wildcardProjection:创建的索引可以支持对任何标量字段的查询,wildcardProjection排除的字段除外

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

Wildcard indexes do not support mixing inclusion and exclusion statements in the wildcardProjection document except when explicitly including the _id field. 通配符索引不支持在wildcardProjection文档中混合包含和排除语句,除非明确包含_id字段。For more information on wildcardProjection, see the parameter documentation.有关wildcardProjection的更多信息,请参阅参数文档

Create Index 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 option 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", or a simple majority of data-bearing voting members:以下操作创建一个提交法定人数"majority"的索引,或包含投票成员数据的简单多数:

db.getSiblingDB("examples").runCommand(
  {
    createIndexes: "invoices",
    indexes: [
      {
        key: { "invoices" : 1 },
        "name" : "invoiceIndex"
      }
    ],
    "commitQuorum" : "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.有关索引构建和投票过程的更多信息,请参阅复制环境中的索引构建

Output输出

The createIndexes command returns a document that indicates the success of the operation. createIndexes命令返回指示操作成功的文档。The document contains some but not all of the following fields, depending on outcome:根据结果,文档包含以下部分但不是全部字段:

createIndexes.createdCollectionAutomatically

If true, then the collection didn't exist and was created in the process of creating the index.如果为true,则表示集合不存在,并且是在创建索引的过程中创建的。

createIndexes.numIndexesBefore

The number of indexes at the start of the command.命令开始时的索引数。

createIndexes.numIndexesAfter

The number of indexes at the end of the command.命令末尾的索引数。

createIndexes.ok

A value of 1 indicates the indexes are in place. 1表示索引已到位。A value of 0 indicates an error.0表示错误。

createIndexes.note

This note is returned if an existing index or indexes already exist. 如果现有索引已存在,则返回此注释。This indicates that the index was not created or changed.这表示未创建或更改索引。

createIndexes.errmsg

Returns information about any errors.返回有关任何错误的信息。

createIndexes.code

The error code representing the type of error.表示错误类型的错误代码。

←  createcurrentOp →