Given the following query: db.books.find( { "category": "kids books", "price": { "$lt": 20.00 } } ).sort( { "number_sold": -1 } ) Which index on the books collection will be the most performant for the above query? Choose the best answer:
Answer options
- A.{"number_sold": 1, "category": 1, "price": 1}
- B.{"price": 1, "number_sold": 1, "category": 1}
- C.{"category": 1, "price": 1, "number_sold": 1}
- D.{"number_sold": 1, "price": 1, "category": 1}
- E.{"category": 1, "number_sold": 1, "price": 1}
Answer confidence: High
Correct answer: E
Explanation language: Chinese
按 ESR 规则(等值 → 排序 → 范围)排列字段:category 是等值条件、number_sold 是排序字段、price 是范围条件,所以最优索引是 { category: 1, number_sold: 1, price: 1 }。C 把 price 放在排序字段之前,索引无法支撑排序;A、D 以 number_sold 开头,无法用 category 做前缀等值定位、只能全索引扫描;B 同样用不上 category 的等值匹配。单字段排序可由索引反向扫描实现,所以 number_sold: 1 也能满足 sort: -1。