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
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 A
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
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 B
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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.