An index covers a query when the index contains all of the fields scanned by the query. A covered query scans the index and not the collection, which improves query performance.当索引包含查询扫描的所有字段时,索引会覆盖查询。覆盖查询扫描索引而不是集合,这提高了查询性能。
Indexes can also partially support queries if a subset of the fields queried are indexed.如果查询的字段子集被索引,索引也可以部分支持查询。
About this Task关于此任务
A single collection can have a maximum of 64 indexes. However, too many indexes can degrade performance before that limit is reached. For collections with a high write-to-read ratio, indexes can degrade performance because each insert must also update any indexes.一个集合最多可以有64个索引。然而,在达到该限制之前,过多的索引可能会降低性能。对于具有高读写比的集合,索引可能会降低性能,因为每次插入都必须更新任何索引。
Steps步骤
Identify common queries识别常见查询
To identify common query patterns in your application, use the 要识别应用程序中的常见查询模式,请使用$queryStats aggregation stage. $queryStats reports metrics for query shapes, which group queries based on shared fields.$queryStats聚合阶段。$queryStats报告查询形状的度量,这些形状根据共享字段对查询进行分组。
Create indexes to support common queries创建索引以支持常见查询
After you know which fields your application frequently queries, you can create indexes to support queries on those fields. For more information, see Examples.在知道应用程序经常查询哪些字段后,您可以创建索引来支持对这些字段的查询。有关更多信息,请参阅示例。
Analyze index use分析指标使用情况
After your application begins using indexes, you can analyze your indexes' effectiveness. To see index statistics and usage, you can:在应用程序开始使用索引后,您可以分析索引的有效性。要查看索引统计信息和使用情况,您可以:
Use the使用$indexStatsaggregation stage.$indexStats聚合阶段。For MongoDB Atlas deployments, view Indexes in the Atlas UI.对于MongoDB Atlas部署,请在Atlas UI中查看索引。
Consider deleting unused indexes to improve application performance. For more information, see Remove Unnecessary Indexes.考虑删除未使用的索引以提高应用程序性能。有关详细信息,请参阅删除不必要的索引。
Repeat this procedure periodically to ensure that your indexes support your current workload.定期重复此过程,以确保索引支持当前的工作负载。
Examples示例
Create a Single-Key Index创建单键索引
If your application only queries on a single key in a given collection, then you need to create a single-key index for that collection. For example, you can create an index on 如果您的应用程序只查询给定集合中的单个键,那么您需要为该集合创建一个单键索引。例如,您可以在category in the product collection:product(产品)集合中创建category(类别)索引:
db.products.createIndex( { category: 1 } )
The preceding index supports this query:前面的索引支持此查询:
db.products.find( { category: "electronics" } )Create a Compound Index创建复合索引
If your application performs queries on both a single key and multiple keys, a compound index is more efficient than a single-key index. For example, you can create an index on the 如果应用程序对单键和多键都执行查询,则复合索引比单键索引更有效。例如,您可以在category, item, and location fields:category、item和location字段上创建索引:
db.products.createIndex( { category: 1, item: 1, location: 1 } )Index Prefixes索引前缀
A compound index supports queries on index prefixes, which are the beginning subsets of indexed fields. For example, the preceding index supports these queries:复合索引支持对索引前缀的查询,索引前缀是索引字段的开始子集。例如,前面的索引支持以下查询:
db.products.find( { category: "electronics" } )
db.products.find( { category: "electronics", item: "television" } )
For more information and performance considerations on index prefixes, see Index Prefixes.有关索引前缀的更多信息和性能考虑,请参阅索引前缀。
Create Indexes to Support Text Search创建索引以支持文本搜索
For data hosted on MongoDB, you can support full-text search with MongoDB Search indexes. To learn more, see Create a MongoDB Search Index.对于托管在MongoDB上的数据,您可以使用MongoDB搜索索引支持全文搜索。要了解更多信息,请参阅创建MongoDB搜索索引。
For self-managed (non-Atlas) deployments, MongoDB provides a 对于自我管理(非Atlas)部署,MongoDB提供了一种text index type that supports searching for string content in a collection. To learn more about self-managed text indexes, see Text Indexes on Self-Managed Deployments.text索引类型,支持在集合中搜索字符串内容。要了解有关自我管理文本索引的更多信息,请参阅自我管理部署上的文本索引。
Create Vector Search Indexes创建矢量搜索索引
Vector Search Indexes support queries on vector embeddings. To create Vector Search Indexes, see Index Fields for Vector Search.矢量搜索索引支持对矢量嵌入的查询。要创建矢量搜索索引,请参阅矢量搜索的索引字段。
Index Use and Collation索引使用和排序
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 score and the string field category; the index is created with the collation locale "fr" for string comparisons:restaurants在数字字段score和score以及字符串字段类别上有一个复合索引;索引是使用排序规则区域设置“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.与文档键(包括嵌入式文档键)的匹配使用简单的二进制比较。这意味着,无论您为强度参数设置了什么值,对类似"type.café"的键的查询都不会与键"type.cafe"匹配。