0
0
MongoDBquery~5 mins

Index direction (ascending vs descending) in MongoDB - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Index direction (ascending vs descending)
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of matching documents grows, the number of index entries scanned grows roughly the same.

Input Size (n)Approx. Operations
10About 10 index entries scanned
100About 100 index entries scanned
1000About 1000 index entries scanned

Pattern observation: The number of operations grows linearly with the number of matching documents, regardless of index direction.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we added a compound index with mixed directions? How would that affect the time complexity of queries using that index?