mongodb 如何决定查询使用哪个索引?

How does mongodb decide which index to use for a query?

当对mongodb集合做某个查询时,如果有多个索引可以用来执行查询,mongodb如何选择索引进行查询?

例如,在 'order' 集合中,如果 'customer' 和 'vendor' 列有两个索引,并且发出了指定客户和供应商的查询,如何mongodb 决定是使用客户索引还是供应商索引?

对于给定的查询,有没有办法指示 mongodb 优先选择某个索引而不是另一个索引?

他们的官方网站声明:

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.

您可以查看 This article 了解更多信息

对于您的第二个查询,您可以尝试为文档创建自定义索引。查看他们的 Documentation 是否相同

When a certain query is done on a mongodb collection, if there are multiple indexes that can be used to perform the query, how does mongodb choose the index for the query?

你可以生成一个query plan for a query you are trying to analyze - see what indexes are used and how they are used. Use the explain method for this; e.g. db.collection.explain().find(). The explain takes a parameter with values "queryPlanner" (the default), "executionStats" and "allPlansExecution". Each of these have different plan output

查询优化器为可用于给定查询的所有索引生成计划。在您的示例 order 集合中,两个单字段索引(字段 customervendor 各一个)是可能的候选对象(对于具有这两个字段的查询过滤器)。优化器使用每个计划并在一定时间内执行它们,然后选择性能最佳的候选者(这是根据以下因素确定的——哪个在最短的时间内返回了最多的文档,以及其他因素)。基于此它将输出 winningrejected计划,这些可以在 计划输出 中查看。您将在输出中看到获胜计划中的一个索引和被拒绝计划中的另一个索引。

MongoDB 缓存给定查询形状的计划。查询计划已缓存,因此每次执行查询时都无需生成计划并相互比较。


Is there a way to instruct mongodb to prefer a certain index over another, for a given query?

您可以使用以下几种方法:

  1. 使用hint()方法强制MongoDB使用特定索引
  2. 设置 Index Filters 以指定 优化程序将为查询形状评估 的索引。请注意,此设置在服务器关闭后不会保留。