0
0
MongodbHow-ToBeginner · 3 min read

How to Use $sort in Aggregation in MongoDB

In MongoDB aggregation, use the $sort stage to order documents by specified fields. Provide a document with field names as keys and 1 for ascending or -1 for descending order. Place $sort inside the aggregation pipeline to control the output order.
📐

Syntax

The $sort stage takes a document where each key is a field name and the value is either 1 for ascending order or -1 for descending order.

Example: { $sort: { field1: 1, field2: -1 } } sorts first by field1 ascending, then by field2 descending.

json
{
  $sort: { <field1>: 1, <field2>: -1, ... }
}
💻

Example

This example sorts a collection of products by price in ascending order and then by name in descending order.

mongodb
db.products.aggregate([
  { $sort: { price: 1, name: -1 } }
])
Output
[ { "_id": 1, "name": "Banana", "price": 5 }, { "_id": 3, "name": "Apple", "price": 5 }, { "_id": 2, "name": "Carrot", "price": 10 } ]
⚠️

Common Pitfalls

  • Using $sort outside an aggregation pipeline will cause an error; it must be inside aggregate().
  • Sorting on fields that do not exist in some documents can lead to unexpected order.
  • Remember to use 1 for ascending and -1 for descending; other values are invalid.
mongodb
/* Wrong: Using $sort outside aggregation */
db.products.find().sort({ price: 1 }) // This is valid for find but not aggregation

/* Correct: Using $sort inside aggregation */
db.products.aggregate([
  { $sort: { price: 1 } }
])
📊

Quick Reference

UsageDescription
{ $sort: { field: 1 } }Sort documents by field ascending
{ $sort: { field: -1 } }Sort documents by field descending
{ $sort: { field1: 1, field2: -1 } }Sort by field1 ascending, then field2 descending

Key Takeaways

Use $sort inside the aggregation pipeline to order documents.
Specify 1 for ascending and -1 for descending order per field.
Multiple fields can be sorted by listing them in the $sort document.
Sorting on missing fields may affect the order unexpectedly.
Do not use $sort outside aggregate() as it will cause errors.