db.collection.createIndexes()
On this page本页内容
Definition定义Options选项Options for All Index Types所有索引类型的选项Option for Collation排序规则选项Options fortext
Indexestext
索引选项Options for2dsphere
Indexes2dsphere
索引的选项Options for2d
Indexes2d
索引选项Options forwildcard
indexeswildcard
索引选项Behaviors行为Recreating an Existing Index重新创建现有索引Index Options索引选项Wildcard Indexes通配符索引Transactions事务Example实例Create Indexes Without Options创建不带选项的索引Create Indexes with Collation Specified创建指定排序规则的索引Create a Wildcard Index创建通配符索引Create Indexes With Commit Quorum使用提交仲裁创建索引Create Multiple Indexes创建多个索引Additional Information附加信息
Definition定义
db.collection.createIndexes( [ keyPatterns ], 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:Creates one or more indexes on a collection.在集合上创建一个或多个索引。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.createIndexes()
takes the following parameters:采用以下参数:Parameter参数Type类型Description描述keyPatterns
document An array containing index specification documents. Each document contains field and value pairs where the field is the index key and the value describes the type of index for that field.包含索引规范文档的数组。每个文档都包含字段和值对,其中字段是索引键,值描述该字段的索引类型。For an ascending index on a field, specify a value of对于字段的升序索引,请指定值1
; for descending index, specify a value of-1
.1
;对于递减索引,请指定值-1
。
MongoDB supports several different index types, including: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.有关详细信息,请参阅通配符索引。
options
document Optional.可选的。A document that contains a set of options that controls the creation of the indexes.一个文档,包含一组控制索引创建的选项。See Options for details.有关详细信息,请参阅选项。commitQuorum
integer or string Optional.可选的。The minimum number of data-bearing voting replica set members (i.e. commit quorum), including the primary, that must report a successful index build before the primary marks the在主索引将索引标记为就绪之前,必须报告成功生成索引的带有投票副本集成员(即commit quorum)(包括主索引)的最小数据数。indexes
as ready.A "voting" member is any replica set member where“有投票权”成员是members[n].votes
is greater than0
.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 usingsetIndexCommitQuorum
.0
的情况下启动索引生成,则以后无法使用setIndexCommitQuorum
修改提交仲裁。A replica set tag name.复制副本集标记名称。
New in version 4.4.4.4版新增。
Options选项
The options
document contains a set of options that control the creation of the indexes. options
文档包含一组控制索引创建的选项。Different index types can have additional options specific for that type.不同的索引类型可以具有特定于该类型的其他选项。
Multiple index options can be specified in the same document. 可以在同一文档中指定多个索引选项。However, if you specify multiple option documents the 但是,如果指定了多个选项文档,则db.collection.createIndexes()
operation will fail.db.collection.createIndexes()
操作将失败。
Consider the following 考虑以下db.collection.createIndexes()
operation:db.collection.createIndexes()
操作:
db.collection.createIndexes(
[
{
"a": 1
},
{
"b": 1
}
],
{
unique: true,
sparse: true,
expireAfterSeconds: 3600
}
)
If the options specification had been split into multiple documents like this: 如果将选项规范拆分为多个文档,如{ unique: true }, { sparse: true, expireAfterSeconds: 3600 }
the index creation operation would have failed.{ unique: true }, { sparse: true, expireAfterSeconds: 3600 }
,则索引创建操作将失败。
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:除非另有指定,否则以下选项可用于所有索引类型:
unique | boolean | keyPatterns array is a unique index. keyPatterns 数组中指定的每个索引都是唯一的索引。true to create a unique index. true 可创建唯一索引。false .false 。 |
name | string | db.collection.createIndexes() apply to all of the index specifications included in the key pattern array. db.collection.createIndexes() 指定的选项适用于键模式数组中包含的所有索引规范。db.collection.createIndexes() . db.collection.createIndexes() 创建单个索引时才能指定名称。 |
partialFilterExpression | document |
partialFilterExpression option for all MongoDB index types. partialFilterExpression 选项。 |
sparse | boolean | true , the indexes only reference documents with the specified fields. true ,则索引仅引用具有指定字段的文档。false . See Sparse Indexes for more information.false 。有关详细信息,请参阅稀疏索引。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 |
expireAfterSeconds | integer | expireAfterSeconds value must be within 0 and 2147483647 inclusive. expireAfterSeconds 值必须介于0 和2147483647 之间(包括0 和2147463647 )。 |
hidden | boolean | Default is false . |
storageEngine | document | storageEngine option should take the following form: storageEngine 选项应采用以下形式:storageEngine: { <storage-engine-name>: <options> }
|
Option for Collation排序规则选项
collation | document | collation
collation 选项具有以下语法:collation: { locale field is mandatory; all other collation fields are optional. locale 字段是必需的;所有其他排序规则字段都是可选的。 |
The following indexes only support simple binary comparison and do not support collation:以下索引仅支持简单的二进制比较,不支持排序规则:
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将使用指定的排序规则创建索引。
By specifying a collation 通过指定排序规则strength
of 1
or 2
, you can create a case-insensitive index. strength
为1
或2
,可以创建不区分大小写的索引。Index with a collation 排序规则strength
of 1
is both diacritic- and case-insensitive.strength
为1
的索引不区分重音符号和大小写。
You can create multiple indexes on the same key(s) with different collations. 可以使用不同的排序规则在同一个键上创建多个索引。To create indexes with the same key pattern but different collations, you must supply unique index names.若要创建具有相同键模式但排序规则不同的索引,必须提供唯一的索引名称。
To use an index for string comparisons, an operation must also specify the same collation. 若要使用索引进行字符串比较,操作还必须指定相同的排序规则。That is, an index with a collation cannot support an operation that performs string comparisons on the indexed fields if the operation specifies a different collation.也就是说,如果具有排序规则的索引指定了不同的排序规则,则该索引无法支持对索引字段执行字符串比较的操作。
For example, the collection 例如,集合myColl
has an index on a string field category
with the collation locale "fr"
.myColl
在排序规则区域设置为"fr"
的字符串字段category
上有一个索引。
db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )
The following query operation, which specifies the same collation as the index, can use the index:以下查询操作指定与索引相同的排序规则,可以使用索引:
db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )
However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:但是,以下查询操作(默认情况下使用“简单”二进制排序器)不能使用索引:
db.myColl.find( { category: "cafe" } )
For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys.对于索引前缀键不是字符串、数组和嵌入文档的复合索引,指定不同排序规则的操作仍然可以使用索引来支持对索引前缀键的比较。
For example, the collection 例如,集合myColl
has a compound index on the numeric fields score
and price
and the string field category
; the index is created with the collation locale "fr"
for string comparisons:myColl
对数字字段score
和price
以及字符串字段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:"simple"
二进制排序规则进行字符串比较,可以使用索引:
db.myColl.find( { score: 5 } ).sort( { price: 1 } )
db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } )
The following operation, which uses 以下操作使用"simple"
binary collation for string comparisons on the indexed category
field, can use the index to fulfill only the score: 5
portion of the query:"simple"
二进制排序规则对索引category
字段进行字符串比较,可以使用索引仅完成查询的score: 5
部分:
db.myColl.find( { score: 5, category: "cafe" } )
Options for text
Indexestext
索引选项
text
IndexesThe following options are available for text indexes only:以下选项仅适用于text
索引:
weights | document | text 索引,包含字段和权重对的文档。1 .1 。weights 选项只允许用于文本索引。 |
default_language | string | text 索引,确定停止词列表以及词干生成器和标记生成器规则的语言。english .english 。 |
language_override | string | text 索引,是集合文档中包含文档替代语言的字段的名称。language . language 。 |
textIndexVersion | integer | text index version number. Users can use this option to override the default version number.text 索引版本号。用户可以使用此选项覆盖默认版本号。text 索引版本。 |
Options for 2dsphere
Indexes2dsphere
索引的选项
2dsphere
IndexesThe following option is available for 2dsphere indexes only:以下选项仅适用于2dsphere
索引:
2dsphereIndexVersion | integer | 2dsphere index version number. Users can use this option to override the default version number.2dsphere 索引版本号。用户可以使用此选项覆盖默认版本号。2dsphere 索引。 |
Options for 2d
Indexes2d
索引选项
2d
IndexesThe following options are available for 以下选项仅适用于2d
indexes only:2d
索引:
bits | integer | 2d indexes, the number of precision of the stored geohash value of the location data.2d 索引,存储的位置数据的geohash值的精度。bits value ranges from 1 to 32 inclusive. bits 值的范围从1到32(包括1到32)。26 . 26 。 |
min | number | 2d indexes, the lower inclusive boundary for the longitude and latitude values. 2d 索引,经度和纬度值的包含下限。-180.0 .-180.0 。 |
max | number | 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
索引选项
wildcard
indexesThe following option is available for wildcard indexes only:以下选项仅适用于wildcard
索引:
wildcardProjection | document | wildcardProjection option when you create a wildcard index on a specific field path and its subfields.wildcardProjection 选项。wildcardProjection { "$**": 1 } wildcardProjection to exclude duplicated fields from the wildcard pattern.wildcardProjection 从通配符模式中排除重复的字段。wildcardProjection ``{ "path.to.field.$**" : 1 }`` wildcardProjection option takes the following form: wildcardProjection 选项采用以下形式:wildcardProjection: { <value> can be either of the following: <value> 可以是以下任意一种:
_id field by default. _id 字段。_id field in the wildcard index, you must explicitly include it in the wildcardProjection document: _id 字段,必须在wildcardProjection 文档中明确包含该字段:{ wildcardProjection document must be either inclusion or exclusion statements. wildcardProjection 文档中的所有语句都必须是包含语句或排除语句。_id field with exclusion statements. _id 字段包含在排除语句中。db.collection.createIndexes() apply to all of the index specifications included in the key pattern array. db.collection.createIndexes() 指定的选项适用于键模式数组中包含的所有索引规范。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.除了collation
选项之外,如果您使用一组索引选项创建索引,然后尝试使用不同的索引选项重新创建相同的索引,MongoDB将不会更改选项,也不会重新创建索引。
The hidden option can be changed without dropping and recreating the index. 可以在不删除和重新创建索引的情况下更改hidden
选项。See Hidden Option.请参见hidden
选项。
To change the other index options, drop the existing index with 若要更改其他索引选项,请在使用新选项运行db.collection.dropIndex()
before running db.collection.createIndexes()
with the new options.db.collection.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隐藏选项
New in version 4.4. 4.4版新增。
To hide or unhide existing indexes, you can use the following 要隐藏或取消隐藏现有索引,可以使用以下mongosh
methods:mongosh
方法:
For example,例如
To change the要将索引的hidden
option for an index totrue
, use thedb.collection.hideIndex()
method:hidden
选项更改为true
,请使用db.collection.hideIndex()
方法:db.restaurants.hideIndex( { borough: 1, ratings: 1 } );
To change the要将索引的hidden
option for an index tofalse
, use thedb.collection.unhideIndex()
method:hidden
选项更改为false
,请使用db.collection.unhideIndex()
方法:db.restaurants.unhideIndex( { borough: 1, city: 1 } );
See also: 另请参阅:
Wildcard Indexes通配符索引
Wildcard indexes omit the默认情况下,通配符索引会省略_id
field by default._id
字段。To include the要在通配符索引中包含_id
field in the wildcard index, you must explicitly include it in thewildcardProjection
document:_id
字段,必须在wildcardProjection
文档中明确包含该字段:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}All of the statements in the通配符Projection文档中的所有语句都必须是包含语句或排除语句。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._id
字段包含在exclusion语句中。这是该规则的唯一例外。Wildcard indexes do not support:通配符索引不支持:2d (Geospatial) indexes2d(地理空间)索引2dsphere (Geospatial) indexes2dsphere(地理空间)索引Hashed indexes哈希索引Time to Live (TTL) indexes生存时间(TTL)索引Text indexes文本索引Unique indexes唯一索引
Wildcard indexes are sparse indexes.通配符索引是sparse
索引。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 (从MongoDB 7.0开始,通配符索引支持升序(1
) and descending (-1
) sort order. Earlier versions only supported ascending order.1
)和降序(-1
)排序顺序。早期版本仅支持升序。
To learn more, see:要了解更多信息,请参阅:
Transactions事务
Changed in version 4.4.4.4版更改。
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从MongoDB 4.4开始,如果多文档事务不是跨分片写入事务,则可以在该事务内创建集合和索引。
To use 若要在事务中使用db.collection.createIndexes()
in a transaction, the transaction must use read concern "local"
. db.collection.createIndexes()
,该事务必须使用读取关注"local"
。If you specify a read concern level other than 如果指定了"local"
, the transaction fails."local"
以外的读取关注级别,则事务将失败。
See also: 另请参阅:
Example实例
See also: 另请参阅:
db.collection.createIndex()
for examples of various index specifications.用于各种索引规范的示例。
Create Indexes Without Options创建不带选项的索引
Consider a 考虑一个包含类似以下文档的restaurants
collection containing documents that resemble the following:restaurants
集合:
{
location: {
type: "Point",
coordinates: [-73.856077, 40.848447]
},
name: "Morris Park Bake Shop",
cuisine: "Cafe",
borough: "Bronx",
}
The following example creates two indexes on the 以下示例在restaurants
collection: an ascending index on the borough
field and a 2dsphere index on the location
field.restaurants
集合上创建两个索引:borough
字段上的升序索引和location
字段上的2dsphere
索引。
db.restaurants.createIndexes([{"borough": 1}, {"location": "2dsphere"}])
Create Indexes with Collation Specified创建指定排序规则的索引
The following example creates two indexes on the 以下示例在products
collection: an ascending index on the manufacturer
field and an ascending index on the category
field. products
集合上创建两个索引:manufacturer
(制造商)字段上的升序索引和类别字段上的降序索引。Both indexes use a collation that specifies the locale 两个索引都使用一个fr
and comparison strength 2
:collation
,该排序规则指定区域设置fr
和比较强度2
:
db.products.createIndexes( [ { "manufacturer": 1}, { "category": 1 } ],
{ collation: { locale: "fr", strength: 2 } })
For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. 对于使用相同排序规则的索引键的查询或排序操作,MongoDB可以使用索引。For details, see Collation and Index Use.有关详细信息,请参阅排序规则和索引使用。
Create a Wildcard Index创建通配符索引
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在单个字段路径上创建通配符索引Create a Wildcard Index on All Field Paths在所有字段路径上创建通配符索引Create a Wildcard Index on Multiple Specific Field Paths在多个特定字段路径上创建通配符索引Omit Specific Fields from Wildcard Index Coverage从通配符索引覆盖范围中省略特定字段
Create a Wildcard Index on a Single Field Path在单个字段路径上创建通配符索引
Consider a collection 考虑一个集合products_catalog
where documents may contain a product_attributes
field. products_catalog
,其中文档可能包含product_attributes
字段。The product_attributes
field can contain arbitrary nested fields, including embedded documents and arrays:product_attributes
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
The following operation creates a wildcard index on the 以下操作在product_attributes
field:product_attributes
字段上创建通配符索引:
use inventory
db.products_catalog.createIndexes(
[ { "product_attributes.$**" : 1 } ]
)
With this wildcard index, MongoDB indexes all scalar values of 通过这个通配符索引,MongoDB为product_attributes
. 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" } } )
The path-specific wildcard index syntax is incompatible with the 特定于路径的通配符索引语法与wildcardProjection
option. See the parameter documentation for more information.wildcardProjection
选项不兼容。有关详细信息,请参阅参数文档。
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
字段可以包含任意嵌套字段,包括嵌入的文档和数组:
{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"product_name" : "Blaster Gauntlet",
"product_attributes" : {
"price" : {
"cost" : 299.99
"currency" : USD
}
...
}
},
{
"_id" : ObjectId("5c1d358bf383fbee028aea0c"),
"product_name" : "Super Suit",
"product_attributes" : {
"superFlight" : true,
"resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
...
},
}
The following operation creates a wildcard index on all scalar fields (excluding the 以下操作在所有标量字段(不包括_id
field):_id
字段)上创建通配符索引:
use inventory
db.products_catalog.createIndexes( [ { "$**" : 1 } ] )
With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. 通过这个通配符索引,MongoDB为集合中的每个文档的所有标量字段建立索引。If a given field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.如果给定字段是嵌套文档或数组,则通配符索引会递归到文档/数组中,并对文档/数组的所有标量字段进行索引。
The created index can support queries on any arbitrary field within documents in the collection:创建的索引可以支持对集合中文档中任意字段的查询:
db.products_catalog.find( { "product_price" : { $lt : 25 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )
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.elements
和product_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的完整文档,请参阅通配符索引的选项。wildcardProjection
, see Options for wildcard
indexes.
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" } )
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.elements
和product_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 } )
Wildcard indexes do not support mixing inclusion and exclusion statements in the 通配符索引不支持在wildcardProjection
document except when explicitly including the _id
field. wildcardProjection
文档中混合包含和排除语句,除非显式包含_id
字段。For more information on 有关wildcardProjection
, see the parameter documentation.wildcardProjection
的更多信息,请参阅参数文档。
Create Indexes With Commit Quorum使用提交仲裁创建索引
Requires 需要featureCompatibilityVersion 4.4+
Each 副本集或分片集群中的每个mongod
in the replica set or sharded cluster must have featureCompatibilityVersion set to at least 4.4
to start index builds simultaneously across replica set members.mongod
必须将featureCompatibilityVersion
设置为至少4.4
,才能在副本集成员之间同时启动索引构建。
MongoDB 4.4 running MongoDB 4.4运行featureCompatibilityVersion: "4.2"
builds indexes on the primary before replicating the index build to secondaries.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 要设置提交仲裁,请使用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
):CA
)和华盛顿州(WA
)蛋糕销售的cakeSales
系列:
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
).orderDate
上,按升序(1
)排列,state
按降序(-1
)排列。
Additional Information附加信息
For additional information about indexes, refer to:有关索引的其他信息,请参阅:
The Indexes section of this manual for full documentation of indexes and indexing in MongoDB.本手册的索引部分提供了MongoDB中索引和索引的完整文档。db.collection.getIndexes()
to view the specifications of existing indexes for a collection.以查看集合的现有索引的规范。Text Indexes for details on creating有关创建text
indexes.text
索引的详细信息,请参阅text
索引。Geospatial Indexes for geospatial queries.用于地理空间查询的geospatial
索引。TTL Indexes for expiration of data.用于数据过期的TTL
索引。