How do you sort the result?
To sort results in MongoDB, use the sort() method.
Example:
js
db.users.find().sort({ age: 1 })1 sorts ascending,
-1 sorts descending.
A descending example:
js
db.users.find().sort({ age: -1 })The logic:
-
sort()takes an object where the key is the field to sort by, and the value is the direction (1or-1). -
You can sort by several fields at once:
jsdb.users.find().sort({ age: 1, name: -1 })
Summary: sort() changes the order documents come back in, letting you sort by one or several fields, ascending or descending.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.