有一个集合people
,索引如下:
{"first_name": 1, "address.state": -1, "address.city": -1, "ssn": 1}
对于过滤和排序, 以下哪些查询将使用索引?
{ "first_name": { $gt: "J"} }).sort({ "address.city": -1 }
{ "first_name": "Jessica"}).sort({ "address.state": 1, "address.city": 1 }
{ "first_name": "Jessica", "address.state": { $lt: "S"} }).sort({ "address.state": 1 }
{"address.city":"West Cindy"}).sort({ "address.city":-1}
{"address.state":"South Dakota","first_name": "Jessica"}).sort({ "address.city":-1}
我已经完成了以下问题: Which of the following queries will use the index?
但它只解释了用于过滤的索引,我需要对过滤器和排序功能都使用索引。
另外,如何判断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 类(class) Lab 2.1 的作业问题,所以我很了解数据集。我将逐个选择-
-
{ "first_name": { $gt: "J" } }).sort({ "address.city": -1 }
它不能成为选项,因为排序是在地址城市上进行的,因此不能乱序使用索引。 { "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 })
上面的查询返回一个响应,它没有像 "stage": "SORT" 这样的东西,它告诉我们排序发生在数据库中使用索引。如果我们有 Stage SORT,那么它会告诉我们排序发生在 RAM 中,而 DB 无法使用索引在数据库中进行排序。
{ "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 能够使用索引进行排序。
{"address.city":"West Cindy"}).sort({ "address.city":-1}
忽略这个,因为索引不是从左边开始的。{"address.state":"South Dakota","first_name": "Jessica"}).sort({ "address.city":-1}
这与选项 2 相同。我执行了类似的查询,但没有获得任何 SORT 阶段,因此它使用索引进行排序。
使用索引进行过滤,非常容易识别。如果ex.find(<Your query>)
给出一个 "stage": "COLLSCAN" 然后索引不用于过滤。选项 2、3、5 在 ex.find() 响应中没有 "stage": "COLLSCAN"因此它们使用索引进行过滤。
通过这种方式,我确保所有选项都使用索引进行过滤和排序。
您还可以为选项 1 和 4 运行 ex.find() ,您将得到 "stage": "COLLSCAN"或 "stage": "SORT",分别表明索引未用于过滤或排序。
谢谢...
关于mongodb - 过滤和排序 以下哪些查询将使用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502029/