Refer to the exhibit. Why is the query execution plan performing a FETCH stage after an IXSCAN, and how can it be optimized?
Exhibit
db.collection.find({status: 'active', type: 'user'}).sort({created: -1}).explain('executionStats')
'winningPlan': {
'stage': 'FETCH',
'inputStage': {
'stage': 'IXSCAN',
'keyPattern': { status: 1, type: 1 }
}
}Trap 1: The index is missing the 'status' field, causing a scan.
The execution plan shows that the index {status: 1, type: 1} is being successfully used in an IXSCAN stage. The problem is not the absence of the equality fields, but the lack of the sorting field within the index structure to avoid memory-intensive operations.
Trap 2: The query is not using an index at all.
The execution plan clearly displays an IXSCAN stage, which confirms that an index is currently being utilized. The bottleneck identified is the combination of the index and the sort operation, not a lack of an index. Therefore, index optimization is the correct path forward.
Trap 3: Remove the index to improve write throughput.
Removing an index will force the database to perform a collection scan, which is the most expensive operation in MongoDB. This would drastically degrade read performance. The goal is to optimize the read path while balancing the write cost, not to eliminate indexes entirely.
- A
The index is missing the 'status' field, causing a scan.
Why it fails: The execution plan shows that the index {status: 1, type: 1} is being successfully used in an IXSCAN stage. The problem is not the absence of the equality fields, but the lack of the sorting field within the index structure to avoid memory-intensive operations.
- B
Change the index to {status: 1, type: 1, created: -1}.
Including the sort field 'created' in the compound index allows the database to retrieve documents in the desired order directly from the B-tree. This removes the need for an in-memory sort or a FETCH stage, significantly reducing latency and memory overhead for the query execution.
- C
The query is not using an index at all.
Why it fails: The execution plan clearly displays an IXSCAN stage, which confirms that an index is currently being utilized. The bottleneck identified is the combination of the index and the sort operation, not a lack of an index. Therefore, index optimization is the correct path forward.
- D
Remove the index to improve write throughput.
Why it fails: Removing an index will force the database to perform a collection scan, which is the most expensive operation in MongoDB. This would drastically degrade read performance. The goal is to optimize the read path while balancing the write cost, not to eliminate indexes entirely.