0
0
MongoDBquery~5 mins

Sorting by multiple fields in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does sorting by multiple fields mean in MongoDB?
It means arranging documents in order based on more than one field, for example, first by age, then by name.
Click to reveal answer
beginner
How do you specify sorting order for multiple fields in MongoDB?
You provide an object to sort() with field names as keys and 1 for ascending or -1 for descending as values, like { age: 1, name: -1 }.
Click to reveal answer
beginner
What happens if two documents have the same value in the first sorted field?
MongoDB uses the next field in the sort order to decide which document comes first.
Click to reveal answer
intermediate
Write a MongoDB query to sort users first by score descending, then by username ascending.
db.users.find().sort({ score: -1, username: 1 })
Click to reveal answer
beginner
Why is sorting by multiple fields useful in real life?
It helps organize data clearly, like sorting a contact list by last name and then first name, so people with the same last name are grouped and ordered by first name.
Click to reveal answer
In MongoDB, how do you sort documents by two fields, age ascending and name descending?
Asort({ age: 'asc', name: 'desc' })
Bsort({ age: -1, name: 1 })
Csort({ age: 1, name: -1 })
Dsort(['age', 'name'])
What does the number -1 mean in a MongoDB sort object?
ASort descending
BSort ascending
CIgnore the field
DSort randomly
If two documents have the same value in the first sorted field, what does MongoDB do?
ADeletes one document
BReturns an error
CLeaves them unordered
DSorts by the next field in the sort object
Which of these is a valid MongoDB sort command to sort by price ascending and rating descending?
Asort({ price: 1, rating: -1 })
Bsort({ price: -1, rating: 1 })
Csort({ price: 'asc', rating: 'desc' })
Dsort(price, rating)
Why might you want to sort by multiple fields in a database?
ATo make data look random
BTo organize data clearly when one field alone is not enough
CTo delete duplicate data
DTo speed up queries
Explain how to sort documents by multiple fields in MongoDB and why it is useful.
Think about sorting by age then name.
You got /4 concepts.
    Write a MongoDB query to sort a collection by two fields: first descending by date, then ascending by title.
    Use 1 for ascending and -1 for descending.
    You got /2 concepts.