Sorting by multiple fields helps you organize data clearly when one field alone is not enough. It lets you order results by more than one rule.
0
0
Sorting by multiple fields in MongoDB
Introduction
You want to list students first by grade, then by name alphabetically.
You need to show products sorted by category and then by price within each category.
You want to display events sorted by date and then by start time.
You want to order employees by department and then by their joining date.
Syntax
MongoDB
db.collection.find().sort({ field1: 1, field2: -1 })Use 1 for ascending order and -1 for descending order.
The order of fields in the sort object matters; sorting happens in that sequence.
Examples
Sort students by grade ascending, then by name ascending.
MongoDB
db.students.find().sort({ grade: 1, name: 1 })Sort products by category ascending, then by price descending.
MongoDB
db.products.find().sort({ category: 1, price: -1 })Sort events by date ascending, then by start time ascending.
MongoDB
db.events.find().sort({ date: 1, startTime: 1 })Sample Program
This inserts four employees and then sorts them by department ascending, and within each department by join year ascending.
MongoDB
db.employees.insertMany([
{ name: "Alice", department: "HR", joinYear: 2020 },
{ name: "Bob", department: "HR", joinYear: 2019 },
{ name: "Charlie", department: "IT", joinYear: 2021 },
{ name: "David", department: "IT", joinYear: 2019 }
])
const sortedEmployees = db.employees.find().sort({ department: 1, joinYear: 1 }).toArray()
sortedEmployeesOutputSuccess
Important Notes
Sorting by multiple fields is like sorting a phone book by last name, then first name.
If two documents have the same value in the first field, the second field decides their order.
Summary
Sorting by multiple fields lets you organize data with more detail.
Use 1 for ascending and -1 for descending order for each field.
The order of fields in the sort object controls the sorting priority.