mongodb复合索引的ESR原则

For compound indexes, this rule of thumb is helpful in deciding the order of fields in the index:

  1. First, add those fields against which Equality queries are run.
  2. The next fields to be indexed should reflect the Sort order of the query.
  3. The last fields represent the Range of data to be accessed.

出处: https://www.mongodb.com/blog/post/performance-best-practices-indexing

简单来说就是索引的字段顺序应该是等值查询字段最前面,然后是排序字段,最后是范围查询字段。
这是一个超级有用的小原则。关于mongodb查询性能优化,这系列文章讲得还挺不错的。这篇也有提到一个小技巧:

To determine whether a query is a covered query, use the explain() method. If the explain() output displays totalDocsExamined as 0, this shows the query is covered by an index.

实用。