MongoDB Aggregation $sort

MongoDB Aggregation $sort 🔃
What does $sort do?
Orders documents ascending or descending
Works on single or multiple fields
Commonly combined with
$limit,$skip,$groupSimilar to ORDER BY in SQL
Basic Syntax
📌 -1 = Descending
1️⃣ Sort by a Single Field
Example: Sort students by age (ascending)
Descending
2️⃣ Sort by Multiple Fields
Example: Sort by course (ASC) then age (DESC)
📌 First sorts by course, then by age within each course.
3️⃣ $sort with $limit (Top N Records)
Top 5 oldest students
⚠️ $sort must come before $limit.
4️⃣ $sort After $group
Example: Courses with most students
5️⃣ $sort with $match (Best Practice 👍)
📌 Filter first, then sort → better performance
6️⃣ Sorting Text Fields (A–Z / Z–A)
SQL vs MongoDB $sort
SQL
MongoDB
$sort vs sort() in find()
$sort | sort() |
|---|---|
| Aggregation stage | Cursor method |
Works with $group | No grouping |
| Advanced pipelines | Simple queries |
Example:
Performance Tips ⚡
Use indexes on sort fields
Place
$matchbefore$sortAvoid sorting large datasets without indexes
Common Mistakes ❌
Using
$limitbefore$sortSorting without indexes on big collections
Expecting numeric sort on string fields
