Definition定义
db.collection.createIndex(keys, options, commitQuorum)Creates indexes on collections.在集合上创建索引。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The createIndex() method has the following form:createIndex()方法具有以下形式:
db.collection.createIndex( <keys>, <options>, <commitQuorum>)
The createIndex() method takes the following parameters:createIndex()方法接受以下参数:
keys |
| |
options | ||
commitQuorum |
|
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:除非另有说明,否则以下选项适用于所有索引类型:
unique |
| |
name | ||
partialFilterExpression |
| |
sparse |
| |
expireAfterSeconds |
| |
hidden |
| |
storageEngine |
|
Option for Collation排序规则选项
collation |
|
The following indexes only support simple binary comparison and do not support collation:以下索引仅支持简单的二进制比较,不支持排序规则:
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. Index with a collation strength of 1 is both diacritic- and case-insensitive.strength指定为1或2,可以创建不区分大小写的索引。排序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.要使用索引进行字符串比较,操作还必须指定相同的排序规则。也就是说,如果操作指定了不同的排序规则,则具有排序规则的索引无法支持对索引字段执行字符串比较的操作。
Warning
Because indexes that are configured with collation use ICU collation keys to achieve sort order, collation-aware index keys may be larger than index keys for indexes without collation.因为配置了排序规则的索引使用ICU排序键来实现排序顺序,所以对于没有排序规则的指数,具有排序规则意识的索引键可能比索引键大。
A restaurants collection has the following documents:restaurants集合有以下文件:
db.restaurants.insertMany( [
{ _id: 1, category: "café", status: "Open" },
{ _id: 2, category: "cafe", status: "open" },
{ _id: 3, category: "cafE", status: "open" }
] )
The restaurants collection has an index on a string field category with the collation locale "fr".restaurants集合在排序规则为"fr"的字符串字段category上有一个索引。
db.restaurants.createIndex( { category: 1 }, { collation: { locale: "fr" } } )
The following query, which specifies the same collation as the index, can use the index:以下查询指定了与索引相同的排序规则,可以使用索引:
db.restaurants.find( { category: "cafe" } ).collation( { locale: "fr" } )
However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:但是,以下查询操作(默认情况下使用“简单”二进制排序器)不能使用索引:
db.restaurants.find( { category: "cafe" } )
For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys.对于索引前缀键不是字符串、数组和嵌入式文档的复合索引,指定不同排序规则的操作仍然可以使用索引来支持对索引前缀键的比较。
For example, the collection 例如,集合restaurants has a compound index on the numeric fields score and price and the string field category; the index is created with the collation locale "fr" for string comparisons:restaurants在数字字段score和price以及字符串字段category上有一个复合索引;索引是使用排序规则区域设置"fr"创建的,用于字符串比较:
db.restaurants.createIndex(
{ score: 1, price: 1, category: 1 },
{ collation: { locale: "fr" } } )
The following operations, which use 以下使用"simple" binary collation for string comparisons, can use the index:"simple"二进制排序规则进行字符串比较的操作可以使用索引:
db.restaurants.find( { score: 5 } ).sort( { price: 1 } )
db.restaurants.find( { score: 5, price: { $gt: Decimal128( "10" ) } } ).sort( { price: 1 } )
The following operation, which uses 以下操作使用"simple" binary collation for string comparisons on the indexed category field, can use the index to fulfill only the score: 5 portion of the query:"simple"二进制排序规则对索引category字段进行字符串比较,可以使用索引仅完成查询的score: 5部分:
db.restaurants.find( { score: 5, category: "cafe" } )
To confirm whether a query used an index, run the query with the 要确认查询是否使用了索引,请使用explain() option.explain()选项运行查询。
Important
Matches against document keys, including embedded document keys, use simple binary comparison. This means that a query for a key like "type.café" will not match the key "type.cafe", regardless of the value you set for the strength parameter.与文档键(包括嵌入式文档键)的匹配使用简单的二进制比较。这意味着,无论您为strength参数设置了什么值,对类似“type.café”的键的查询都不会与键“type.cafe”匹配。
Options for text Indexestext索引选项
text IndexesThe following options are available for text indexes only:以下选项仅适用于text索引:
weights |
| |
default_language | text索引,确定停用词列表的语言以及词干分析器和标记器的规则。english.english。 | |
language_override | language. text索引,集合文档中包含文档覆盖语言的字段的名称。默认值是language。 | |
textIndexVersion |
|
Options for 2dsphere Indexes2dsphere索引选项
2dsphere IndexesThe following option is available for 2dsphere indexes only:以下选项仅适用于2dsphere索引:
2dsphereIndexVersion |
|
Options for 2d Indexes2d索引选项
2d IndexesThe following options are available for 2d indexes only:以下选项仅适用于2d索引:
bits |
| |
min | 2d indexes, the lower inclusive boundary for the longitude and latitude values. The default value is -180.0.2d索引,经度和纬度值的下限。默认值为-180.0。 | |
max | 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 IndexesWildcard indexes通配符索引 can use the 可以使用wildcardProjection option.wildcardProjection(通配符投影)选项。
wildcardProjection |
|
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.除排序规则选项外,如果您使用一组索引选项创建索引,然后尝试使用不同的索引选项重新创建相同的索引,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隐藏选项
To hide or unhide existing indexes, you can use the following 要隐藏或取消隐藏现有索引,可以使用以下mongosh methods:mongosh方法:
For example,例如,
To change the要将索引的hiddenoption for an index totrue, use thedb.collection.hideIndex()method:hidden选项更改为true,请使用db.collection.hideIndex()方法:db.restaurants.hideIndex( { borough: 1, ratings: 1 } );To change the要将索引的hiddenoption for an index tofalse, use thedb.collection.unhideIndex()method:hidden选项更改为false,请使用db.collection.unhideIndex()方法:db.restaurants.unhideIndex( { borough: 1, city: 1 } );
Transactions事务
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.如果分布式事务不是跨分片写入事务,则可以在该事务内创建集合和索引。
To use 要在事务中使用db.collection.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"以外的读取关注级别,则事务失败。
Index Builds索引构建
Changed in version 7.1.在版本7.1中的更改。
Starting in MongoDB 7.1, index builds are improved with faster error reporting and increased failure resilience. You can also set the minimum available disk space required for index builds using the new 从MongoDB 7.1开始,索引构建得到了改进,错误报告更快,故障恢复能力更强。您还可以使用新的indexBuildMinAvailableDiskSpaceMB parameter, which stops index builds if disk space is too low.indexBuildMinAvailableDiskSpaceMB参数设置索引构建所需的最小可用磁盘空间,如果磁盘空间太低,该参数将停止索引构建。
The following table compares the index build behavior starting in MongoDB 7.1 with earlier versions.下表将MongoDB 7.1中开始的索引构建行为与早期版本进行了比较。
| An index build error can cause a secondary member to crash.停止索引构建的请求并不总是可能的:如果一个成员已经投票提交了索引,那么辅助成员就不能请求停止索引构建,辅助成员就会崩溃(类似于MongoDB 7.0和更早版本)。索引构建错误可能会导致辅助成员崩溃。 | |
indexBuildMinAvailableDiskSpaceMB parameter. indexBuildMinAvailableDiskSpaceMB参数中指定的最小值,则索引构建可能会自动停止。 |
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 } )
Compound indexes can include a single hashed field. Compound hashed indexes require featureCompatibilityVersion set to at least 复合索引可以包含一个5.0.hashed字段。复合哈希索引需要将featureCompatibilityVersion设置为至少5.0。
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. The example creates the index with the collation that specifies the locale fr and comparison strength 2:category_fr的索引。该示例使用指定区域设置fr和比较强度2的排序规则创建索引:
db.restaurants.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.date_category_f的复合索引。排序规则仅适用于具有字符串值的索引键。
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. 对于使用相同排序规则的索引键的查询或排序操作,MongoDB可以使用索引。The indexes use collation of 索引使用强度strength: 2, which results in case-insensitive queries when the index is used. strength: 2,这会在使用索引时导致不区分大小写的查询。For details, see Collation and Index Use.有关详细信息,请参阅排序规则和索引使用。
Create a Wildcard Index创建通配符索引
Wildcard indexes omit the默认情况下,通配符索引省略_idfield by default. To include the_idfield in the wildcard index, you must explicitly include it in thewildcardProjectiondocument:_id字段。要在通配符索引中包含_id字段,您必须在wildcardProjection文档中明确包含它:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}All of the statements in thewildcardProjectiondocument must be either inclusion or exclusion statements. You can also include the_idfield with exclusion statements. This is the only exception to the rule.wildcardProjection文档中的所有语句都必须是包含或排除语句。您还可以在排除语句中包含_id字段。这是这条规则的唯一例外。Wildcard indexes do not support:通配符索引不支持:2d(Geospatial) indexes(地理空间)索引2dsphere(Geospatial) indexes(地理空间)索引Hashedindexes索引Time to Live (TTL) indexes生存时间(TTL)索引Text indexes全文索引Unique indexes唯一索引
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通配符索引是稀疏索引。当索引字段不存在时,它们不支持查询。如果通配符字段为nullvalue.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:要了解更多信息,请参阅:
For examples, see:例如,请参阅:
Create a Wildcard Index on a Single Field Path在单个字段路径上创建通配符索引Create a Wildcard Index on All Field Paths在所有字段路径上创建通配符索引Include Specific Fields in Wildcard Index Coverage在通配符索引覆盖率中包含特定字段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. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:
db.products_catalog.insertMany( [
{
_id : ObjectId("5c1d358bf383fbee028aea0b"),
product_name: "Blaster Gauntlet",
product_attributes: {
price: {
cost: 299.99,
currency: "USD"
}
}
},
{
_id: ObjectId("5c1d358bf383fbee028aea0c"),
product_name: "Super Suit",
product_attributes: {
superFlight: true,
resistance: [ "Bludgeoning", "Piercing", "Slashing" ]
}
}
] )
The following operation creates a wildcard index on the 以下操作在product_attributes field:product_attributes字段上创建通配符索引:
use inventory
db.products_catalog.createIndex( { "product_attributes.$**" : 1 } )
With this wildcard index, MongoDB indexes all scalar values of 使用此通配符索引,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.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. 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字段可以包含任意嵌套字段,包括嵌入式文档和数组:
db.products_catalog.insertMany( [
{
_id : ObjectId("5c1d358bf383fbee028aea0b"),
product_name: "Blaster Gauntlet",
product_attributes: {
price: {
cost: 299.99,
currency: "USD"
}
}
},
{
_id: ObjectId("5c1d358bf383fbee028aea0c"),
product_name: "Super Suit",
product_attributes: {
superFlight: true,
resistance: [ "Bludgeoning", "Piercing", "Slashing" ]
}
}
] )
The following operation creates a wildcard index on all scalar fields (excluding the 以下操作在所有标量字段(_id field):_id字段除外)上创建通配符索引:
use inventory
db.products_catalog.createIndex( { "$**" : 1 } )
With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.使用此通配符索引,MongoDB对集合中每个文档的所有标量字段进行索引。如果给定字段是嵌套文档或数组,通配符索引将递归到文档/数组中,并对文档/数组的所有标量字段进行索引。
The created index can support queries on any arbitrary field within documents in the collection:创建的索引可以支持对集合中文档中任意字段的查询:
db.products_catalog.find( { "product_price" : { $lt : 25 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )
Note
Wildcard indexes omit the 默认情况下,通配符索引省略_id field by default. _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. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:
db.products_catalog.insertMany( [
{
_id : ObjectId("5c1d358bf383fbee028aea0b"),
product_name: "Blaster Gauntlet",
product_attributes: {
price: {
cost: 299.99,
currency: "USD"
}
}
},
{
_id: ObjectId("5c1d358bf383fbee028aea0c"),
product_name: "Super Suit",
product_attributes: {
superFlight: true,
resistance: [ "Bludgeoning", "Piercing", "Slashing" ]
}
}
] )
The following operation creates a wildcard index and uses the 以下操作创建通配符索引,并使用wildcardProjection option to include only scalar values of the product_attributes.elements and product_attributes.resistance fields in the index.wildcardProjection选项在索引中仅包含product_attributes.elements和product_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. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:products_catalog,其中文档可能包含product_attributes字段。product_attributes字段可以包含任意嵌套字段,包括嵌入式文档和数组:
db.products_catalog.insertMany( [
{
_id : ObjectId("5c1d358bf383fbee028aea0b"),
product_name: "Blaster Gauntlet",
product_attributes: {
price: {
cost: 299.99,
currency: "USD"
}
}
},
{
_id: ObjectId("5c1d358bf383fbee028aea0c"),
product_name: "Super Suit",
product_attributes: {
superFlight: true,
resistance: [ "Bludgeoning", "Piercing", "Slashing" ]
}
}
] )
This example uses a wildcard index and a 此示例使用通配符索引和wildcardProjection document to index the scalar fields for each document in the collection.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.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+需要功能兼容性版本4.4+
Each 副本集或分片集群中的每个mongod in the replica set or sharded cluster must have featureCompatibilityVersion set to at least 4.4 to start index builds simultaneously across replica set members.mongod都必须将featureCompatibilityVersion设置为至少4.4,才能在副本集成员之间同时启动索引构建。
Index builds on a replica set or sharded cluster build simultaneously across all data-bearing replica set members. 索引基于副本集构建,或在所有承载数据的副本集成员之间同时构建分片集群。For sharded clusters, the index build occurs only on shards containing data for the collection being indexed. 对于分片集群,索引构建仅发生在包含被索引集合的数据的分片上。The primary requires a minimum number of data-bearing 初选需要最少数量的数据承载voting members (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. voting成员(即提交法定人数),包括其本身,在将索引标记为可供使用之前,必须完成构建。See Index Builds in Replicated Environments for more information.有关更多信息,请参阅复制环境中的索引构建。
To set the commit quorum, use 要设置提交法定人数,请使用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 on Self-Managed Deployments for details on creating有关创建文本索引的详细信息,请参阅自我管理部署上的文本索引。textindexes.Geospatial Indexes for geospatial queries.地理空间查询的地理空间索引。TTL Indexes for expiration of data.数据过期的TTL索引。