With index { batch: 1, dob: 1 }, following query performs 2 index seeks and performs sort merge
db.Students.find({ batch: {$in: [2001, 2004]} }).sort({ dob: -1 }).limit(10000).explain("executionStats");
winningPlan: {
stage: 'LIMIT',
limitAmount: 10000,
inputStage: {
stage: 'FETCH',
inputStage: {
stage: 'SORT_MERGE',
sortPattern: { dob: 1 },
inputStages: [
{
stage: 'IXSCAN',
keyPattern: { batch: 1, dob: 1 },
indexName: 'batch_1_dob_1',
isMultiKey: false,
multiKeyPaths: { batch: [], dob: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: {
batch: [ '[2001, 2001]' ],
dob: [ '[MinKey, MaxKey]' ]
}
},
{
stage: 'IXSCAN',
keyPattern: { batch: 1, dob: 1 },
indexName: 'batch_1_dob_1',
isMultiKey: false,
multiKeyPaths: { batch: [], dob: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: {
batch: [ '[2004, 2004]' ],
dob: [ '[MinKey, MaxKey]' ]
}
}
]
}
}
}
Then why does db.Students.find().sort({ batch: 1, dob: -1 }).limit(5)
query with index { batch: 1, dob: -1 }
does similar thing. For each batch scan the index backwards and merge the final result.
I know that sort order in query should match index order. I want to know the reason behind this limitaiton.
Why we cannot perform backward scans with multiple index seeks ?