Sorting With sort() and Multiple Keys
Learners will sort query results by one or more fields in ascending and descending order and see how sort interacts with index usage.
Ordering Query Results With sort()
The sort() method appended to a find() cursor tells MongoDB to return documents in a specific order. Pass an object where each key is a field name and each value is 1 (ascending) or -1 (descending). Sorting happens on the server before documents are sent to the client, so you receive results in order regardless of how many documents match.
// Ascending: oldest first
db.posts.find({}).sort({ createdAt: 1 });
// Descending: newest first
db.posts.find({}).sort({ createdAt: -1 });
// With Node.js driver
const posts = await db.collection('posts')
.find({})
.sort({ createdAt: -1 })
.toArray();Sorting by Multiple Keys
MongoDB sorts by the first key first, then uses subsequent keys to break ties. Pass multiple fields in the sort object. The order of keys matters: the first key is the primary sort, the second is the tiebreaker. A common example is sorting products by category ascending, then by price descending within each category.
// Primary sort: category ASC; secondary sort: price DESC
db.products.find({}).sort({ category: 1, price: -1 });
// Sorting users by role then by username alphabetically
db.users.find({}).sort({ role: 1, username: 1 });
// Sorting blog posts: featured first, then newest
db.posts.find({}).sort({ isFeatured: -1, createdAt: -1 });All lessons in this course
- Sorting With sort() and Multiple Keys
- Skip and Limit: Offset Pagination
- Keyset Pagination With Range Queries
- Combining Sort, Skip, Limit, and Projections