sort method ascending and descending in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we sort data in MongoDB, the time it takes depends on how much data there is.
We want to understand how sorting time grows as the data size grows.
Analyze the time complexity of the following code snippet.
// Sort documents by age ascending
db.users.find().sort({ age: 1 })
// Sort documents by age descending
db.users.find().sort({ age: -1 })
This code sorts user documents by their age field in ascending or descending order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and rearranging documents based on the age field.
- How many times: The sorting algorithm compares many pairs of documents, roughly
O(n log n)where n is the number of documents.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: As the number of documents grows, the number of comparisons grows faster than the number of documents, roughly O(n log n).
Time Complexity: O(n log n)
This means sorting takes more time as data grows, but not as fast as checking every pair; it grows in a balanced way.
[X] Wrong: "Sorting always takes the same time no matter how many documents there are."
[OK] Correct: Sorting needs to compare and reorder documents, so more documents mean more work and more time.
Understanding how sorting time grows helps you explain database performance clearly and shows you know how data size affects operations.
"What if we add an index on the age field? How would the time complexity of sorting change?"
Practice
sort({ age: 1 }) method do in MongoDB?Solution
Step 1: Understand the sort method parameter
The number 1 insort({ age: 1 })means ascending order.Step 2: Interpret the sorting effect
Documents will be arranged from smallest age to largest age.Final Answer:
Sorts documents by age in ascending order (smallest to largest) -> Option DQuick Check:
sort({ field: 1 }) = ascending order [OK]
- Confusing 1 with descending order
- Thinking sort filters data
- Assuming sort deletes documents
score in descending order in MongoDB?Solution
Step 1: Check the correct object syntax for sort
The sort method requires an object with field name as key and 1 or -1 as value, inside curly braces.Step 2: Identify descending order syntax
Descending order is indicated by -1, so{ score: -1 }is correct.Final Answer:
db.collection.find().sort({ score: -1 }) -> Option AQuick Check:
sort({ field: -1 }) = descending order [OK]
- Missing curly braces around sort argument
- Using parentheses instead of braces
- Putting -1 as key instead of value
db.students.find().sort({ score: 1 })?Solution
Step 1: Understand ascending sort by score
Sorting by score ascending means from smallest to largest score: 78, 85, 92.Step 2: Map scores to names in order
78 = Cara, 85 = Anna, 92 = Ben, so order is ["Cara", "Anna", "Ben"].Final Answer:
["Cara", "Anna", "Ben"] -> Option CQuick Check:
sort({ score: 1 }) = ascending order [OK]
- Mixing ascending with descending order
- Sorting by name instead of score
- Confusing array order in output
db.products.find().sort({ price: 2 })Solution
Step 1: Check valid sort values
MongoDB sort only accepts 1 for ascending or -1 for descending, not 2.Step 2: Identify the error cause
Using 2 will cause a syntax or runtime error because it's invalid.Final Answer:
The sort value must be 1 or -1, not 2 -> Option BQuick Check:
sort values = 1 or -1 only [OK]
- Using numbers other than 1 or -1
- Assuming any positive number works
- Thinking sort can't chain after find()
category and price. How do you sort first by category ascending, then by price descending?Solution
Step 1: Understand multi-field sort syntax
MongoDB sorts by fields in the order they appear in the object passed to sort().Step 2: Apply ascending to category and descending to price
Use{ category: 1, price: -1 }to sort category ascending, then price descending within each category.Final Answer:
db.collection.find().sort({ category: 1, price: -1 }) -> Option AQuick Check:
Multi-field sort = object with fields in order [OK]
- Reversing field order changes sort priority
- Trying to chain multiple sort() calls
- Using wrong sort values for fields
