I'm learning about mongodb index and I would like to ask a question. I read the documentation about mongodb index. But I don't undertand a thing.
I have created a
index price(-1)
If I use a
sort price(1)
Does this sort use the index?
Yes. MongoDB
can scan an index from both directions, so it doesn't really matter what order your index is in. It only matters when you have a compound index (with multiple fields), where you can still start an index scan from both sides on the first field, but the next ones are fixed by the order you give them.
Nevertheless, MongoDB may also traverse the index in either directions. As a result, for single-field indexes, ascending and descending indexes are interchangeable. This is not the case for compound indexes: in compound indexes, the direction of the sort order can have a greater impact on the results.
From the MongoDB
documentation.
The answer is YES.
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"
}
Note cursors are: "BtreeCursor price_-1 reverse", and "BtreeCursor price_-1". Mongodb will use the "reverse index" automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With