Index direction (ascending vs descending) in MongoDB - Performance Comparison
When using indexes in MongoDB, the direction of the index (ascending or descending) can affect how quickly queries run.
We want to understand if changing the index direction changes how the query time grows as data grows.
Analyze the time complexity of queries using ascending and descending indexes.
// Create ascending index
db.collection.createIndex({ age: 1 })
// Create descending index
db.collection.createIndex({ age: -1 })
// Query using ascending index
db.collection.find({ age: { $gte: 30 } }).sort({ age: 1 })
// Query using descending index
db.collection.find({ age: { $gte: 30 } }).sort({ age: -1 })
This code creates two indexes on the same field but with different directions, then runs queries that use those indexes.
Look at what repeats when the query runs:
- Primary operation: Scanning index entries matching the query condition.
- How many times: Once per matching document in the index range.
As the number of matching documents grows, the number of index entries scanned grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 index entries scanned |
| 100 | About 100 index entries scanned |
| 1000 | About 1000 index entries scanned |
Pattern observation: The number of operations grows linearly with the number of matching documents, regardless of index direction.
Time Complexity: O(n)
This means the query time grows in a straight line with the number of matching documents, whether the index is ascending or descending.
[X] Wrong: "Using descending indexes is slower than ascending indexes because the order is reversed."
[OK] Correct: MongoDB treats ascending and descending indexes the same way internally, so the direction does not affect how fast the query runs.
Understanding that index direction does not change time complexity helps you focus on what really matters: choosing the right fields to index for your queries.
What if we added a compound index with mixed directions? How would that affect the time complexity of queries using that index?