Sort the MongoDB documents in ascending order with aggregation?

To sort MongoDB documents in ascending order with aggregation, use the $sort stage in the aggregation pipeline with field: 1 (ascending) or field: -1 (descending).

Syntax

db.collection.aggregate([
    { $sort: { fieldName: 1 } }  // 1 for ascending, -1 for descending
]);

Sample Data

db.demo652.insertMany([
    {
        value: 10,
        "details": [
            {
                "ProductName": "Product-1",
                "ProductQuantity": 8,
                "ProductPrice": 500
            },
            {
                "ProductName": "Product-2",
                "ProductQuantity": 7,
                "ProductPrice": 500
            }
        ]
    },
    {
        value: 5,
        "details": [
            {
                "ProductName": "Product-1",
                "ProductQuantity": 8,
                "ProductPrice": 500
            },
            {
                "ProductName": "Product-2",
                "ProductQuantity": 7,
                "ProductPrice": 500
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9f0730e3c3cd0dcff36a62"),
        ObjectId("5e9f0740e3c3cd0dcff36a63")
    ]
}

Example: Sort by Value Field

Sort the documents by the value field in ascending order using aggregation ?

db.demo652.aggregate([
    { $unwind: "$details" },
    { $match: {} },
    {
        $group: {
            "ProductPrice": {
                "$first": "$value"
            },
            "details": {
                "$push": {
                    "ProductName": "$details.ProductName"
                }
            },
            "_id": "$_id"
        }
    },
    {
        $sort: {
            "ProductPrice": 1
        }
    },
    {
        $project: {
            "_id": 0,
            "ProductPrice": 1,
            "details": 1
        }
    }
]);
{
    "ProductPrice": 5,
    "details": [
        {
            "ProductName": "Product-1"
        },
        {
            "ProductName": "Product-2"
        }
    ]
}
{
    "ProductPrice": 10,
    "details": [
        {
            "ProductName": "Product-1"
        },
        {
            "ProductName": "Product-2"
        }
    ]
}

Key Points

  • Use $sort: { field: 1 } for ascending order and { field: -1 } for descending order.
  • Place $sort stage after any grouping operations for better performance.
  • Multiple fields can be sorted: { field1: 1, field2: -1 }.

Conclusion

The $sort stage in MongoDB aggregation pipeline sorts documents by specified fields. Use 1 for ascending and -1 for descending order to organize your query results effectively.

Updated on: 2026-03-15T03:24:54+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements