Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb descending ascending index

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?

like image 917
Carlota Viña Avatar asked Feb 12 '23 03:02

Carlota Viña


2 Answers

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.

like image 59
i3arnon Avatar answered Feb 24 '23 16:02

i3arnon


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.

like image 35
Mark_H Avatar answered Feb 24 '23 17:02

Mark_H