翻译或纠错本页面

查询计划

在给定可用索引的情况下,MongoDB查询优化器处理查询并且选择出针对某查询而言最高效的查询计划。每次查询执行的时候,查询系统都会使用该查询计划。

查询优化器只会对那些看起来有多个可行计划的查询计划进行缓存。

For each query, the query planner searches the query plan cache for an entry that fits the query shape. If there are no matching entries, the query planner generates candidate plans for evaluation over a trial period. The query planner chooses a winning plan, creates a cache entry containing the winning plan, and uses it to generate the result documents.

MongoDB提供了 Query Plan Cache Methods 来查看和修改已缓存的查询计划。

The following diagram illustrates the query planner logic:

Diagram of query planner logic

索引过滤器会决定优化器评估哪一个索引作为一个 query shape 。一个查询形状由查询、排序以及映射说明组成。如果一个给定的查询形状存在一个索引过滤器,优化器将只会考虑过滤器中指定的这些索引。

针对一个给定查询,您可以使用 explain() 方法查看查询计划的统计。 indexing strategies 中的信息可以在您开发的过程中为您提供帮助。

db.collection.explain() provides information on the execution of other operations, such as db.collection.update(). See db.collection.explain() for details.

在 2.6 版更改: 当查询形状中存在一个索引过滤器时,MongoDB将会忽略 hint() 。如果您想了解MongoDB是否对一个查询使用了索引过滤器,您可以检查一下 explain() 输出的 explain.filterSet 字段。

索引过滤器只会影响到优化器评估的索引,优化器有可能会仍然选择集合扫描作为某给定查询形状的优胜方案。

索引过滤器只存在于服务器进程中,在关机之后并不会保存。MongoDB也提供了一个命令手动删除过滤器。

由于索引过滤器重写了优化器以及 hint() 方法预期的操作,请合理使用索引过滤器。

2.6 新版功能: MongoDB provides Query Plan Cache Methods to view and modify the cached query plans. The PlanCache.clear() method flushes the entire plan cache. Users can also clear particular plan cache entries using PlanCache.clearPlansByQuery().

Index Filters

2.6 新版功能.

Index filters determine which indexes the optimizer evaluates for a query shape. A query shape consists of a combination of query, sort, and projection specifications. If an index filter exists for a given query shape, the optimizer only considers those indexes specified in the filter.

When an index filter exists for the query shape, MongoDB ignores the hint(). To see whether MongoDB applied an index filter for a query shape, check the indexFilterSet field of either the db.collection.explain() or the cursor.explain() method.

Index filters only affects which indexes the optimizer evaluates; the optimizer may still select the collection scan as the winning plan for a given query shape.

Index filters exist for the duration of the server process and do not persist after shutdown. MongoDB also provides a command to manually remove filters.

Because index filters overrides the expected behavior of the optimizer as well as the hint() method, use index filters sparingly.

See planCacheListFilters, planCacheClearFilters, and planCacheSetFilter.