Compound index and field order in MongoDB - Time & Space Complexity
When using compound indexes in MongoDB, the order of fields affects how fast queries run.
We want to understand how the query speed changes as data grows, depending on field order.
Analyze the time complexity of this MongoDB query using a compound index.
db.collection.createIndex({ age: 1, score: -1 })
db.collection.find({ age: 25, score: { $gt: 80 } })
This code creates a compound index on age and score, then queries documents with age 25 and score greater than 80.
Look at what repeats when MongoDB uses this index to find matching documents.
- Primary operation: Scanning index entries for matching age and score.
- How many times: Once per matching age value, then scanning score values in order.
As the number of documents grows, the index helps limit how many entries we check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few index entries scanned for age=25, then score filtered quickly |
| 100 | More entries for age=25, but still efficient due to index order |
| 1000 | Still scanning only entries with age=25, score range scanned grows with matches |
Pattern observation: The query scans a small subset of the index, growing mostly with matching score values for the fixed age.
Time Complexity: O(log n + m)
This means MongoDB quickly finds the start point in the index (log n), then scans matching entries (m) for the score condition.
[X] Wrong: "Changing the order of fields in the compound index does not affect query speed."
[OK] Correct: The order controls how MongoDB can use the index to filter quickly; wrong order can cause full scans or ignore parts of the index.
Understanding how compound index order affects query speed shows you know how databases handle data efficiently, a key skill for real projects.
"What if we reversed the index to { score: -1, age: 1 }? How would the time complexity change for the same query?"
Practice
Solution
Step 1: Understand what an index is
An index helps MongoDB find data faster by organizing it.Step 2: Understand compound index purpose
A compound index uses more than one field to speed up queries that use those fields together.Final Answer:
Speeds up queries that filter or sort on multiple fields together -> Option AQuick Check:
Compound index = Speeds up multi-field queries [OK]
- Thinking it stores data in multiple collections
- Confusing with backup or encryption features
- Believing it only indexes one field
age ascending and score descending in MongoDB?Solution
Step 1: Recall syntax for createIndex
MongoDB uses an object with field names and 1 or -1 for ascending/descending.Step 2: Match field order and directions
Age ascending is 1, score descending is -1, so { age: 1, score: -1 } is correct.Final Answer:
db.collection.createIndex({ age: 1, score: -1 }) -> Option AQuick Check:
Use 1/-1 for asc/desc in object [OK]
- Using array instead of object for fields
- Using strings like 'asc' or 'desc' instead of 1/-1
- Mixing ascending and descending incorrectly
{ city: 1, rating: -1 }, which query will use the index efficiently?Solution
Step 1: Understand index field order and directions
The index is on city ascending, then rating descending.Step 2: Check query filter and sort usage
Query B filters on city (first field) and sorts rating descending (matching index direction).Final Answer:
db.collection.find({ city: 'NYC' }).sort({ rating: -1 }) -> Option CQuick Check:
Filter first field, sort second field matching index [OK]
- Sorting rating ascending when index is descending
- Filtering only on rating without city
- Ignoring field order in index
{ a: 1, b: 1 } but your query { b: 5 } is slow. What is the likely issue?Solution
Step 1: Recall how compound indexes work
Compound indexes work best when queries filter on the first field in the index.Step 2: Analyze query filter
The query filters only onb, the second field, so index onathenbis not used efficiently.Final Answer:
The query does not filter on the first indexed fielda-> Option BQuick Check:
Filter must include first index field [OK]
- Thinking MongoDB doesn't support compound indexes
- Believing field order doesn't matter
- Assuming descending order is always required
category and sorting by price ascending. Which compound index is best?Solution
Step 1: Identify query pattern
Queries filter by category and sort by price ascending.Step 2: Choose index field order and direction
Index should have category first (filter), then price ascending (sort) to match query.Final Answer:
db.collection.createIndex({ category: 1, price: 1 }) -> Option DQuick Check:
Filter field first, sort field second with matching order [OK]
- Putting sort field before filter field in index
- Using descending order when query sorts ascending
- Ignoring field order importance
Ready to prove it?
Pass the test and this pattern moves unknown
