Hi everyone.
I have a collection execution
with the following index, among others:
[
{
"v" : 4,
"key" : {
"tenantId" : 1,
"startTime" : 1
},
"name" : "tenantId_1_startTime_1",
"ns" : "executions.execution"
},
]
When I run the query:
db.execution.find({'tenantId': 'a57ff64mr9', 'mode': 'FULL', 'startTime': {$gte: ISODate('2024-06-01T13:00:00.123Z')}, 'endTime': {$lte: ISODate('2024-05-29T13:05:00Z')}}).limit(25).sort({'startTime': 1, direction: -1}).explain('queryPlanner');
I see the index is used:
`
“queryPlanner” : {
“plannerVersion” : 1,
“namespace” : “executions.execution”,
“winningPlan” : {
“stage” : “SUBSCAN”,
“inputStage” : {
“stage” : “LIMIT_SKIP”,
“inputStage” : {
“stage” : “SORT”,
“sortPattern” : {
“direction” : -1,
“startTime” : 1
},
“inputStage” : {
“stage” : “IXSCAN”,
“indexName” : “tenantId_1_startTime_1”,
“direction” : “forward”
}
}
}
}
},
``
However, changing the startTime parameter value changes the query plan:
db.execution.find({'tenantId': 'a57ff64mr9', 'mode': 'FULL', 'startTime': {$gte: ISODate('2024-05-01T13:00:00.123Z')}, 'endTime': {$lte: ISODate('2024-05-29T13:05:00Z')}}).limit(25).sort({'startTime': 1, direction: -1}).explain('queryPlanner');
"queryPlanner" : { "plannerVersion" : 1, "namespace" : "executions.execution", "winningPlan" : { "stage" : "SUBSCAN", "inputStage" : { "stage" : "LIMIT_SKIP", "inputStage" : { "stage" : "SORT", "sortPattern" : { "direction" : -1, "startTime" : 1 }, "inputStage" : { "stage" : "COLLSCAN" } } } } },
The difference I see is that the first query returns 0 results, and the other ones returns the 25 first results out of 16 million that matched the criteria.
It’s not clear for me why the plan changes based on the query param. If someone could provide some guidance, I would really appreciate.
Thanks!