Easiest way to sort an array in MongoDB

The easiest way to sort an array in MongoDB is to use the aggregation pipeline with $unwind, $sort, and $group operators. This approach unwraps the array, sorts the elements, and reconstructs the document.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $sort: { "arrayField.sortField": 1 } },
    { $group: { _id: "$_id", arrayField: { $push: "$arrayField" } } }
]);

Sample Data

db.demo242.insertOne({
    "details2": [
        { "ShipingDate": new ISODate("2019-10-11"), "Price": 1400 },
        { "ShipingDate": new ISODate("2019-10-01"), "Price": 1600 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4429229af932883c61ea44")
}

Display Original Document

db.demo242.find();
{
    "_id": ObjectId("5e4429229af932883c61ea44"), 
    "details2": [
        { "ShipingDate": ISODate("2019-10-11T00:00:00Z"), "Price": 1400 },
        { "ShipingDate": ISODate("2019-10-01T00:00:00Z"), "Price": 1600 }
    ]
}

Sort Array by Date (Ascending)

db.demo242.aggregate([
    { $unwind: "$details2" },
    { $sort: { "details2.ShipingDate": 1 } },
    { $group: { _id: "$_id", details2: { $push: "$details2" } } }
]);
{
    "_id": ObjectId("5e4429229af932883c61ea44"),
    "details2": [
        { "ShipingDate": ISODate("2019-10-01T00:00:00Z"), "Price": 1600 },
        { "ShipingDate": ISODate("2019-10-11T00:00:00Z"), "Price": 1400 }
    ]
}

How It Works

  • $unwind deconstructs the array into separate documents
  • $sort sorts the unwound documents by the specified field
  • $group reconstructs the document with $push to rebuild the sorted array

Conclusion

Use the aggregation pipeline with $unwind, $sort, and $group to sort arrays in MongoDB. This three-stage approach provides complete control over array sorting while preserving document structure.

Updated on: 2026-03-15T02:02:28+05:30

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements