Sorting by multiple fields in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When sorting data by more than one field in MongoDB, the time it takes depends on how many items you have and how the database organizes them.
We want to understand how the sorting time grows as the number of documents increases.
Analyze the time complexity of the following code snippet.
db.collection.find().sort({ age: 1, name: -1 })
This code sorts documents first by the age field in ascending order, then by name in descending order.
- Primary operation: Comparing and ordering each document based on the two fields.
- How many times: Each document is compared multiple times during sorting, roughly proportional to the number of documents.
Sorting time grows faster than just looking at each item once because items must be compared and rearranged.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 comparisons |
| 100 | About 700 to 800 comparisons |
| 1000 | About 10,000 to 12,000 comparisons |
Pattern observation: As the number of documents grows, the number of comparisons grows faster than the number of documents, but not as fast as every pair compared directly.
Time Complexity: O(n log n)
This means sorting takes more time as you add more documents, growing a bit faster than just going through each one once.
[X] Wrong: "Sorting by multiple fields is just as fast as sorting by one field because it's still one sort operation."
[OK] Correct: Sorting by multiple fields means the database compares more details for each pair, so it takes more time than sorting by a single field.
Understanding how sorting time grows helps you explain how databases handle ordering large data sets efficiently, a useful skill in many real projects.
"What if we added an index on the fields used for sorting? How would the time complexity change?"
Practice
Solution
Step 1: Understand sorting purpose
Sorting arranges documents in order based on field values.Step 2: Recognize multiple fields effect
Sorting by multiple fields means ordering by the first field, then by the second if the first is equal, and so on.Final Answer:
Organize data by more than one field in a specific order -> Option AQuick Check:
Sorting by multiple fields = Organize data by multiple fields [OK]
- Confusing sorting with filtering
- Thinking sorting creates or deletes fields
- Assuming sorting only works on one field
age ascending and name descending in MongoDB?Solution
Step 1: Recall sort syntax
MongoDB uses 1 for ascending and -1 for descending order in sort objects.Step 2: Match fields and order
Sorting by age ascending (1) and name descending (-1) matches db.collection.find().sort({age: 1, name: -1}).Final Answer:
db.collection.find().sort({age: 1, name: -1}) -> Option CQuick Check:
age:1, name:-1 syntax = db.collection.find().sort({age: 1, name: -1}) [OK]
- Using strings like 'asc' or 'desc' instead of 1 or -1
- Mixing order of fields incorrectly
- Using wrong signs for ascending/descending
{"name": "Alice", "age": 30, "score": 85}
{"name": "Bob", "age": 25, "score": 90}
{"name": "Alice", "age": 30, "score": 95}What is the order of documents after running
db.collection.find().sort({name: 1, age: -1, score: 1})?Solution
Step 1: Sort by name ascending
Names sorted ascending: "Alice" before "Bob".Step 2: Sort by age descending within same name
Both "Alice" have age 30, so order stays same.Step 3: Sort by score ascending within same name and age
Scores 85 then 95 for "Alice".Final Answer:
[{name: "Alice", age: 30, score: 85}, {name: "Alice", age: 30, score: 95}, {name: "Bob", age: 25, score: 90}] -> Option DQuick Check:
Sort by name↑, age↓, score↑ = [{name: "Alice", age: 30, score: 85}, {name: "Alice", age: 30, score: 95}, {name: "Bob", age: 25, score: 90}] [OK]
- Ignoring order of fields in sort
- Mixing ascending and descending incorrectly
- Assuming score sorts descending by default
db.collection.find().sort({age: 1, name: 2})Solution
Step 1: Check valid sort values
MongoDB accepts only 1 (ascending) or -1 (descending) as sort values.Step 2: Identify invalid value
Value 2 is invalid and causes syntax error.Final Answer:
Using 2 instead of -1 or 1 for sorting order -> Option AQuick Check:
Sort values must be 1 or -1 [OK]
- Using numbers other than 1 or -1
- Confusing sort object syntax
- Assuming 2 means descending
department ascending, then by salary descending, but only for employees with the same department. Which MongoDB query correctly achieves this?Solution
Step 1: Understand sorting priority
Sorting by department ascending means all employees grouped by department alphabetically.Step 2: Sort salary descending within each department
Within each department group, employees are ordered by salary from highest to lowest.Step 3: Match correct sort order
db.employees.find().sort({department: 1, salary: -1}) matches department:1 (ascending) and salary:-1 (descending).Final Answer:
db.employees.find().sort({department: 1, salary: -1}) -> Option BQuick Check:
Sort by department↑ then salary↓ = db.employees.find().sort({department: 1, salary: -1}) [OK]
- Reversing field order in sort object
- Using wrong sort directions
- Assuming sorting salary first groups by salary only
