Sort array in MongoDB query and project all fields?

To sort an array within a document and project all fields in MongoDB, use the aggregation pipeline with $unwind, $sort, $group, and $project stages.

Syntax

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

Sample Data

db.demo252.insertOne({
    "Values": [
        { "v1": 20, "v2": 30 },
        { "v1": 20, "v2": 20 },
        { "v1": 10, "v2": 7 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e46c2761627c0c63e7dba78")
}

Display the document to verify the data:

db.demo252.find();
{ "_id": ObjectId("5e46c2761627c0c63e7dba78"), "Values": [ { "v1": 20, "v2": 30 }, { "v1": 20, "v2": 20 }, { "v1": 10, "v2": 7 } ] }

Example: Sort Array by Multiple Fields

Sort the Values array first by v2 in ascending order, then by v1 in ascending order:

db.demo252.aggregate([
    { $unwind: "$Values" },
    { $sort: { "Values.v2": 1, "Values.v1": 1 } },
    { $group: {
        "_id": "$_id",
        "Values": { $push: "$Values" }
    }},
    { $project: {
        "_id": 1,
        "Values": 1
    }}
]);
{ "_id": ObjectId("5e46c2761627c0c63e7dba78"), "Values": [ { "v1": 10, "v2": 7 }, { "v1": 20, "v2": 20 }, { "v1": 20, "v2": 30 } ] }

How It Works

  • $unwind creates separate documents for each array element
  • $sort orders the unwound documents by specified fields
  • $group reconstructs the array using $push
  • $project shapes the final output to include all desired fields

Conclusion

The aggregation pipeline effectively sorts arrays within documents while preserving all fields. This approach maintains document structure and provides flexible sorting options for complex array operations.

Updated on: 2026-03-15T02:04:10+05:30

719 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements