0
0
MongoDBquery~20 mins

sort method ascending and descending in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MongoDB Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Sort documents by age ascending
Given a collection users with documents containing name and age, what is the output of this query?

db.users.find().sort({age: 1})

Assume the collection has:
{name: 'Alice', age: 30}
{name: 'Bob', age: 25}
{name: 'Carol', age: 35}
MongoDB
db.users.find().sort({age: 1})
A[{name: 'Bob', age: 25}, {name: 'Alice', age: 30}, {name: 'Carol', age: 35}]
B[{name: 'Carol', age: 35}, {name: 'Alice', age: 30}, {name: 'Bob', age: 25}]
C[{name: 'Alice', age: 30}, {name: 'Bob', age: 25}, {name: 'Carol', age: 35}]
D[{name: 'Bob', age: 25}, {name: 'Carol', age: 35}, {name: 'Alice', age: 30}]
Attempts:
2 left
💡 Hint
Sorting by age with 1 means ascending order.
query_result
intermediate
2:00remaining
Sort documents by age descending
Using the same users collection, what is the output of this query?

db.users.find().sort({age: -1})

With documents:
{name: 'Alice', age: 30}
{name: 'Bob', age: 25}
{name: 'Carol', age: 35}
MongoDB
db.users.find().sort({age: -1})
A[{name: 'Bob', age: 25}, {name: 'Alice', age: 30}, {name: 'Carol', age: 35}]
B[{name: 'Alice', age: 30}, {name: 'Carol', age: 35}, {name: 'Bob', age: 25}]
C[{name: 'Carol', age: 35}, {name: 'Bob', age: 25}, {name: 'Alice', age: 30}]
D[{name: 'Carol', age: 35}, {name: 'Alice', age: 30}, {name: 'Bob', age: 25}]
Attempts:
2 left
💡 Hint
Sorting by age with -1 means descending order.
🧠 Conceptual
advanced
1:30remaining
Understanding sort order values
In MongoDB, what do the values 1 and -1 mean when used in the sort() method?
A1 means ascending order, -1 means descending order
B1 means descending order, -1 means ascending order
C1 means sort by string length, -1 means sort by numeric value
D1 means no sorting, -1 means reverse sorting
Attempts:
2 left
💡 Hint
Think about smallest to largest and largest to smallest.
📝 Syntax
advanced
1:30remaining
Identify the invalid sort syntax
Which of the following MongoDB sort method calls will cause a syntax error?
Adb.collection.find().sort({age: 1})
Bdb.collection.find().sort({age: -1})
Cdb.collection.find().sort({age: 'asc'})
Ddb.collection.find().sort({age: 0})
Attempts:
2 left
💡 Hint
Sort values must be numeric 1 or -1.
optimization
expert
2:30remaining
Optimizing sort with index
You have a large MongoDB collection with an index on age. Which query will use the index efficiently for sorting by age descending?
Adb.collection.find().sort({age: 0})
Bdb.collection.find().sort({age: -1})
Cdb.collection.find().sort({name: 1})
Ddb.collection.find().sort({age: 1})
Attempts:
2 left
💡 Hint
Index on age supports sorting by age ascending or descending.