Bird
Raised Fist0
MongoDBquery~20 mins

Sorting by multiple fields in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Sorting Mastery in MongoDB
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2: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})
A[{name: "Zara", age: 25}, {name: "Anna", age: 25}, {name: "Bob", age: 30}]
B[{name: "Bob", age: 30}, {name: "Anna", age: 25}, {name: "Zara", age: 25}]
C[{name: "Anna", age: 25}, {name: "Zara", age: 25}, {name: "Bob", age: 30}]
D[{name: "Anna", age: 25}, {name: "Bob", age: 30}, {name: "Zara", age: 25}]
Attempts:
2 left
💡 Hint
Remember ascending means smallest to largest, descending means reverse alphabetical order.
📝 Syntax
intermediate
1: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})
Adb.records.find().sort({score: -1, date: 1})
Bdb.records.find().sort({score: -1; date: 1})
C)}1 :etad ,1- :erocs{(tros.)(dnif.sdrocer.bd
Ddb.records.find().sort({score: -1 date: 1})
Attempts:
2 left
💡 Hint
Check the punctuation between fields inside the sort object.
optimization
advanced
2:30remaining
Optimizing sorting on multiple fields with indexes
Which index will optimize the query db.orders.find().sort({customerId: 1, orderDate: -1}) best?
AAn index on {orderDate: -1, customerId: 1}
BAn index on {orderDate: 1, customerId: 1}
CAn index on {customerId: 1, orderDate: -1}
DAn index on {customerId: -1, orderDate: 1}
Attempts:
2 left
💡 Hint
Indexes should match the sort fields and their order/direction.
🔧 Debug
advanced
2: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?
AThe collection has no index on category and price, causing inefficient sorting.
BThe sort object keys are unordered, so MongoDB ignores the second field.
CMongoDB sorts only by the first field in the sort object, ignoring others.
DThe query needs a projection to include category and price for sorting.
Attempts:
2 left
💡 Hint
Think about how MongoDB uses indexes to optimize sorting.
🧠 Conceptual
expert
3: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?
ADocuments are sorted randomly because mixed sort directions are not allowed.
BDocuments are sorted by timestamp ascending only, ignoring level.
CDocuments are sorted by level ascending, then timestamp descending.
DDocuments are sorted first by level descending, then by timestamp ascending within each level.
Attempts:
2 left
💡 Hint
The order of fields in the sort object defines precedence.

Practice

(1/5)
1. What does sorting by multiple fields in MongoDB allow you to do?
easy
A. Organize data by more than one field in a specific order
B. Delete multiple fields from documents
C. Create new fields based on existing ones
D. Filter documents by multiple conditions

Solution

  1. Step 1: Understand sorting purpose

    Sorting arranges documents in order based on field values.
  2. 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.
  3. Final Answer:

    Organize data by more than one field in a specific order -> Option A
  4. Quick Check:

    Sorting by multiple fields = Organize data by multiple fields [OK]
Hint: Sorting multiple fields orders by priority fields [OK]
Common Mistakes:
  • Confusing sorting with filtering
  • Thinking sorting creates or deletes fields
  • Assuming sorting only works on one field
2. Which of the following is the correct syntax to sort documents by age ascending and name descending in MongoDB?
easy
A. db.collection.find().sort({name: 1, age: -1})
B. db.collection.find().sort({age: -1, name: 1})
C. db.collection.find().sort({age: 1, name: -1})
D. db.collection.find().sort({age: 'asc', name: 'desc'})

Solution

  1. Step 1: Recall sort syntax

    MongoDB uses 1 for ascending and -1 for descending order in sort objects.
  2. Step 2: Match fields and order

    Sorting by age ascending (1) and name descending (-1) matches db.collection.find().sort({age: 1, name: -1}).
  3. Final Answer:

    db.collection.find().sort({age: 1, name: -1}) -> Option C
  4. Quick Check:

    age:1, name:-1 syntax = db.collection.find().sort({age: 1, name: -1}) [OK]
Hint: Use 1 for ascending, -1 for descending in sort object [OK]
Common Mistakes:
  • Using strings like 'asc' or 'desc' instead of 1 or -1
  • Mixing order of fields incorrectly
  • Using wrong signs for ascending/descending
3. Given the collection documents:
{"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})?
medium
A. [{name: "Alice", age: 30, score: 85}, {name: "Bob", age: 25, score: 90}, {name: "Alice", age: 30, score: 95}]
B. [{name: "Alice", age: 30, score: 95}, {name: "Alice", age: 30, score: 85}, {name: "Bob", age: 25, score: 90}]
C. [{name: "Bob", age: 25, score: 90}, {name: "Alice", age: 30, score: 85}, {name: "Alice", age: 30, score: 95}]
D. [{name: "Alice", age: 30, score: 85}, {name: "Alice", age: 30, score: 95}, {name: "Bob", age: 25, score: 90}]

Solution

  1. Step 1: Sort by name ascending

    Names sorted ascending: "Alice" before "Bob".
  2. Step 2: Sort by age descending within same name

    Both "Alice" have age 30, so order stays same.
  3. Step 3: Sort by score ascending within same name and age

    Scores 85 then 95 for "Alice".
  4. Final Answer:

    [{name: "Alice", age: 30, score: 85}, {name: "Alice", age: 30, score: 95}, {name: "Bob", age: 25, score: 90}] -> Option D
  5. Quick 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]
Hint: Sort priority follows field order in sort object [OK]
Common Mistakes:
  • Ignoring order of fields in sort
  • Mixing ascending and descending incorrectly
  • Assuming score sorts descending by default
4. Identify the error in this MongoDB sort query:
db.collection.find().sort({age: 1, name: 2})
medium
A. Using 2 instead of -1 or 1 for sorting order
B. Missing parentheses after find()
C. Using curly braces instead of square brackets
D. Sorting fields must be strings, not numbers

Solution

  1. Step 1: Check valid sort values

    MongoDB accepts only 1 (ascending) or -1 (descending) as sort values.
  2. Step 2: Identify invalid value

    Value 2 is invalid and causes syntax error.
  3. Final Answer:

    Using 2 instead of -1 or 1 for sorting order -> Option A
  4. Quick Check:

    Sort values must be 1 or -1 [OK]
Hint: Sort values must be 1 or -1, never other numbers [OK]
Common Mistakes:
  • Using numbers other than 1 or -1
  • Confusing sort object syntax
  • Assuming 2 means descending
5. You want to sort a collection by department ascending, then by salary descending, but only for employees with the same department. Which MongoDB query correctly achieves this?
hard
A. db.employees.find().sort({salary: -1, department: 1})
B. db.employees.find().sort({department: 1, salary: -1})
C. db.employees.find().sort({department: -1, salary: 1})
D. db.employees.find().sort({salary: 1, department: -1})

Solution

  1. Step 1: Understand sorting priority

    Sorting by department ascending means all employees grouped by department alphabetically.
  2. Step 2: Sort salary descending within each department

    Within each department group, employees are ordered by salary from highest to lowest.
  3. Step 3: Match correct sort order

    db.employees.find().sort({department: 1, salary: -1}) matches department:1 (ascending) and salary:-1 (descending).
  4. Final Answer:

    db.employees.find().sort({department: 1, salary: -1}) -> Option B
  5. Quick Check:

    Sort by department↑ then salary↓ = db.employees.find().sort({department: 1, salary: -1}) [OK]
Hint: Order fields in sort by priority, use 1 or -1 for direction [OK]
Common Mistakes:
  • Reversing field order in sort object
  • Using wrong sort directions
  • Assuming sorting salary first groups by salary only