我正在学习mongodb索引,想要问一个问题。我已经阅读了有关mongodb索引的文档,但是我不理解其中的一件事。
我创建了一个
索引price(-1)
如果我使用
排序price(1)
这个排序会使用索引吗?
MongoDB
可以从两个方向扫描索引,因此你的索引顺序并不重要。这仅在您有一个复合索引(具有多个字段)时才重要,在该情况下,您仍然可以从第一个字段的两端开始索引扫描,但下一个字段由您给出的顺序固定。MongoDB
文档。rs0:PRIMARY> db.bill.save({price: 100})
rs0:PRIMARY> db.bill.save({price: 110})
rs0:PRIMARY> db.bill.save({price: 120})
rs0:PRIMARY> db.bill.save({price: 130})
rs0:PRIMARY> db.bill.save({price: 140})
rs0:PRIMARY> db.bill.save({price: 150})
rs0:PRIMARY> db.bill.encureIndex({price:-1})
rs0:PRIMARY> db.bill.find().sort({price:1}).explain()
{
"cursor" : "BtreeCursor price_-1 reverse",
"isMultiKey" : false,
"n" : 6,
"nscannedObjects" : 6,
"nscanned" : 6,
"nscannedObjectsAllPlans" : 6,
"nscannedAllPlans" : 6,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 18,
"indexBounds" : {
"price" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
},
"server" : "localhost:27017"
}
rs0:PRIMARY> db.bill.find().sort({price:-1}).explain()
{
"cursor" : "BtreeCursor price_-1",
"isMultiKey" : false,
"n" : 6,
"nscannedObjects" : 6,
"nscanned" : 6,
"nscannedObjectsAllPlans" : 6,
"nscannedAllPlans" : 6,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"price" : [
[
{
"$maxElement" : 1
},
{
"$minElement" : 1
}
]
]
},
"server" : "localhost:27017"
}
db.collection.find({}).sort({price:1}).explain()
{
"cursor": "BtreeCursor x_1",
...
"nscanned": 100
....
}
使用索引的查询计划具有游标类型BtreeCursor。如果查询计划不使用索引,则游标类型为BasicCursor。
hint()
来提示查询规划器反向遍历索引(如果适用),并且你只能使用现有的索引规范或名称进行提示。如果你只有一个基于{price:1}
的索引,那么在{price:-1}
上的提示应该会失败并抛出“坏提示”异常。通常情况下,你应该非常谨慎地使用hint()
。强制使用特定的索引通常会降低性能;最好了解为什么给定查询形状没有使用预期的索引。 - Stennie