Challenge - 5 Problems
Sorting Mastery in MongoDB
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Sorting documents by age ascending then name descending
Given a collection
people with documents containing name and age, what is the output of this query sorting by age ascending and name descending?MongoDB
db.people.find().sort({age: 1, name: -1})Attempts:
2 left
💡 Hint
Remember ascending means smallest to largest, descending means reverse alphabetical order.
✗ Incorrect
The query sorts first by age ascending (25 before 30), then by name descending (Zara before Anna for age 25).
📝 Syntax
intermediate1:30remaining
Identify the syntax error in sorting by multiple fields
Which option contains a syntax error in the MongoDB sort method for sorting by
score descending and date ascending?MongoDB
db.records.find().sort({score: -1, date: 1})Attempts:
2 left
💡 Hint
Check the punctuation between fields inside the sort object.
✗ Incorrect
Option B uses a semicolon instead of a comma between fields, which is invalid syntax in JavaScript objects.
❓ optimization
advanced2:30remaining
Optimizing sorting on multiple fields with indexes
Which index will optimize the query
db.orders.find().sort({customerId: 1, orderDate: -1}) best?Attempts:
2 left
💡 Hint
Indexes should match the sort fields and their order/direction.
✗ Incorrect
The index must start with customerId ascending and then orderDate descending to match the sort exactly.
🔧 Debug
advanced2:30remaining
Why does this multi-field sort not work as expected?
A developer runs
db.products.find().sort({category: 1, price: 1}) but the results are not sorted by price within each category. What is the likely cause?Attempts:
2 left
💡 Hint
Think about how MongoDB uses indexes to optimize sorting.
✗ Incorrect
Without a supporting index, MongoDB may perform an in-memory sort that can be limited or inefficient, causing unexpected order.
🧠 Conceptual
expert3:00remaining
Understanding sort order precedence in MongoDB
If you run
db.logs.find().sort({level: -1, timestamp: 1}), which statement best describes the sorting behavior?Attempts:
2 left
💡 Hint
The order of fields in the sort object defines precedence.
✗ Incorrect
MongoDB sorts by the first field (level descending), then by the second field (timestamp ascending) within groups of the first.