$sort Stage in MongoDB Aggregation Pipeline
1. Definition
The $sort stage is used to arrange documents in a specific order (ascending or descending) based on one or more fields.
2. Simple Understanding
👉 It works like ORDER BY in SQL
👉 It sorts data before sending final results
3. When to Use
- When ordering results
- When showing top or latest data
- When sorting by price, date, or name
- Before applying limit
4. Where it is Used
- Aggregation pipelines
- Search results
- Leaderboard or ranking systems
- Backend APIs
5. Why We Use It
- To organize data meaningfully
- To display ordered results
- To support ranking and pagination
- To prepare data for limit or top queries
6. How It Works
- Uses field values to sort documents
- 1 → ascending order
- -1 → descending order
- Can sort by multiple fields
7. Basic Syntax
db.collection.aggregate([
{ $sort: { age: 1 } } // ascending
]);
db.collection.aggregate([
{ $sort: { age: -1 } } // descending
]);8. Real Example
// Sort users by age (ascending)
db.users.aggregate([
{ $sort: { age: 1 } }
]);
// Sort users by salary (descending)
db.employees.aggregate([
{ $sort: { salary: -1 } }
]);
// Sort by multiple fields
db.users.aggregate([
{ $sort: { role: 1, age: -1 } }
]);9. Explanation
- $sort arranges documents in order
- 1 = ascending, -1 = descending
- Can sort multiple fields
- Often used before $limit
10. Advantages
- Organized output
- Supports ranking systems
- Easy to use
- Works well with indexes
11. Disadvantages
- Sorting large data can be slow
- May consume memory
- Requires index for best performance
Interview Points
- $sort = ORDER BY in SQL
- 1 → ascending, -1 → descending
- Often used with $limit
- Index improves sorting performance