过滤和排序 以下哪些查询将使用索引?

Both Filtering & Sorting Which of following queries will use index?

有一个集合 people 具有以下索引:

{"first_name": 1, "address.state": -1, "address.city": -1, "ssn": 1}

对于过滤和排序, 以下哪些查询将使用索引?

  1. { "first_name": { $gt: "J" } }).sort({ "address.city": -1 }
  2. { "first_name": "Jessica" }).sort({ "address.state": 1, "address.city": 1 }
  3. { "first_name": "Jessica", "address.state": { $lt: "S"} }).sort({ "address.state": 1 }
  4. {"address.city":"West Cindy"}).sort({ "address.city":-1}
  5. {"address.state":"South Dakota","first_name": "Jessica"}).sort({ "address.city":-1}

我已经完成了以下问题:

但它只解释了用于过滤的索引,我需要对过滤器和排序功能都使用索引。

另外,如何判断Index是否同时用于Filter & Sort 或未使用?

Mongo 使用左侧的索引,即 {"first_name": 1, "address.state": -1, "address.city": -1, "ssn": 1} 索引可应用于以下字段查询-

  • {"first_name": 1, "address.state": -1, "address.city": -1, "ssn": 1}
  • {"first_name": 1, "address.state": -1, "address.city": -1}
  • {"first_name": 1, "address.state": -1}
  • {"first_name": 1}

还应注意顺序对于复合索引很重要。

来到这个问题,我知道这是M201课程Lab 2.1的作业问题,所以我很清楚数据集。我会一个一个地选择-

  1. { "first_name": { $gt: "J" } }).sort({ "address.city": -1 } 不能作为选项,因为排序是按地址城市进行的,所以索引不能乱序使用。
  2. { "first_name": "Jessica" }).sort({ "address.state": 1, "address.city": 1 } 可以是选项。为了确保它,我们需要运行 下面查询-

    var ex = db.people.explain();
    ex.find({ "first_name": "Jessica" }).sort({ "address.state": 1, "address.city": 1 })
    

上面的查询 returns 没有类似 "stage" 的响应:"SORT" 告诉我们排序发生在数据库中使用索引。如果我们有 Stage SORT,那么它会告诉我们排序发生在 RAM 中,而 DB 无法使用索引在数据库中进行排序。

  1. { "first_name": "Jessica", "address.state": { $lt: "S"} }).sort({ "address.state": 1 } 我做了和选项 2 一样的操作。

    ex.find({ "first_name": "Jessica", "address.state": { $lt: "S"} }).sort({ "address.state": 1 }) 以上输出没有任何 SORT 阶段,这表明 DB 能够使用索引进行排序。

  2. {"address.city":"West Cindy"}).sort({ "address.city":-1}忽略这个因为索引不是从左开始的

  3. {"address.state":"South Dakota","first_name": "Jessica"}).sort({ "address.city":-1} 这与选项 2 相同。我执行了类似的查询,但没有得到任何 SORT 阶段,因此它使用索引进行排序。

使用索引进行过滤,非常容易识别。如果 ex.find(<Your query>) 给出 "stage" : "COLLSCAN" 则索引未用于过滤。选项 2、3、5 没有 "stage" : "COLLSCAN" 在 ex.find() 响应中,因此这些使用索引进行过滤。

通过这种方式,我确保所有选项都使用索引进行过滤和排序。

你也可以 运行 ex.find() 对于选项 1 和 4 你会得到 "stage" : "COLLSCAN" 或 "stage" : "SORT" 表明索引未分别用于过滤或排序。

谢谢...