Indexing Strategies索引策略

The best indexes for your application must take a number of factors into account, including the kinds of queries you expect, the ratio of reads to writes, and the amount of free memory on your system.应用程序的最佳索引必须考虑许多因素,包括预期的查询类型、读写比以及系统上的可用内存量。

When developing your indexing strategy you should have a deep understanding of your application’s queries. 在开发索引策略时,您应该深入了解应用程序的查询。Before you build indexes, map out the types of queries you will run so that you can build indexes that reference those fields. 在构建索引之前,请列出要运行的查询类型,以便构建引用这些字段的索引。Indexes come with a performance cost, but are more than worth the cost for frequent queries on large data sets. 索引会带来性能成本,但比频繁查询大型数据集的成本更划算。Consider the relative frequency of each query in the application and whether the query justifies an index.考虑应用程序中每个查询的相对频率,以及查询是否对索引进行了验证。

The best overall strategy for designing indexes is to profile a variety of index configurations with data sets similar to the ones you’ll be running in production to see which configurations perform best. 设计索引的最佳总体策略是使用与生产中运行的数据集类似的数据集来分析各种索引配置,以查看哪些配置的性能最佳。Inspect the current indexes created for your collections to ensure they are supporting your current and planned queries. 检查为集合创建的当前索引,以确保它们支持当前和计划的查询。If an index is no longer used, drop the index.如果不再使用索引,请删除该索引。

Generally, MongoDB only uses one index to fulfill most queries. 通常,MongoDB只使用一个索引来完成大多数查询。However, each clause of an $or query may use a different index, and in addition, MongoDB can use an intersection of multiple indexes.然而,$or查询的每个子句可能使用不同的索引,此外,MongoDB可以使用多个索引的交集

The following documents introduce indexing strategies:以下文件介绍了索引策略:

Create Indexes to Support Your Queries创建索引以支持查询
An index supports a query when the index contains all the fields scanned by the query. 当索引包含查询扫描的所有字段时,索引支持查询。Creating indexes that support queries results in greatly increased query performance.创建支持查询的索引可以大大提高查询性能。
Use Indexes to Sort Query Results使用索引对查询结果进行排序
To support efficient queries, use the strategies here when you specify the sequential order and sort order of index fields.要支持高效查询,请在指定索引字段的顺序和排序顺序时使用此处的策略。
Ensure Indexes Fit in RAM确保索引适合RAM
When your index fits in RAM, the system can avoid reading the index from disk and you get the fastest processing.当索引放入RAM时,系统可以避免从磁盘读取索引,从而获得最快的处理速度。
Create Queries that Ensure Selectivity创建确保选择性的查询
Selectivity is the ability of a query to narrow results using the index. 选择性是指查询使用索引缩小结果范围的能力。Selectivity allows MongoDB to use the index for a larger portion of the work associated with fulfilling the query.选择性允许MongoDB将索引用于与完成查询相关的大部分工作。