MongoDB Aggregation $sort

MongoDB Tutorial

MongoDB Aggregation $sort 🔃

In MongoDB, the $sort stage in an Aggregation Pipeline is used to order documents based on one or more fields.

What does $sort do?

  • Orders documents ascending or descending

  • Works on single or multiple fields

  • Commonly combined with $limit, $skip, $group

  • Similar to ORDER BY in SQL


Basic Syntax


📌 1 = Ascending

📌 -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()

$sortsort()
Aggregation stageCursor method
Works with $groupNo grouping
Advanced pipelinesSimple queries

Example:



Performance Tips ⚡

  • Use indexes on sort fields

  • Place $match before $sort

  • Avoid sorting large datasets without indexes


Common Mistakes ❌

  • Using $limit before $sort

  • Sorting without indexes on big collections

  • Expecting numeric sort on string fields


Quick Recap 🧠


 

You may also like...