Sort MongoDB Collection by Array value?

To sort MongoDB collection by Array value, use aggregate() along with $unwind and $sort. This approach first deconstructs the array elements into separate documents, then sorts by the desired array field.

Syntax

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

Sample Data

db.demo577.insertOne({
    "student": {
        "details": [
            {
                "Name": "Chris",
                "Score": 45
            },
            {
                "Name": "Bob", 
                "Score": 33
            },
            {
                "Name": "David",
                "Score": 48
            }
        ]
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e916ff1581e9acd78b427ff")
}

Display Sample Data

db.demo577.find();
{
    "_id": ObjectId("5e916ff1581e9acd78b427ff"),
    "student": {
        "details": [
            { "Name": "Chris", "Score": 45 },
            { "Name": "Bob", "Score": 33 },
            { "Name": "David", "Score": 48 }
        ]
    }
}

Example: Sort by Score (Descending)

db.demo577.aggregate([
    { $unwind: "$student" },
    { $unwind: "$student.details" },
    { $sort: { "student.details.Score": -1 } }
]);
{ "_id": ObjectId("5e916ff1581e9acd78b427ff"), "student": { "details": { "Name": "David", "Score": 48 } } }
{ "_id": ObjectId("5e916ff1581e9acd78b427ff"), "student": { "details": { "Name": "Chris", "Score": 45 } } }
{ "_id": ObjectId("5e916ff1581e9acd78b427ff"), "student": { "details": { "Name": "Bob", "Score": 33 } } }

How It Works

  • $unwind: "$student" − Deconstructs the student object
  • $unwind: "$student.details" − Deconstructs the details array into separate documents
  • $sort: {"student.details.Score": -1} − Sorts by Score field in descending order (-1)

Conclusion

Use $unwind to flatten array elements into individual documents, then apply $sort on the desired array field. This technique enables sorting collections based on values within nested arrays effectively.

Updated on: 2026-03-15T03:43:53+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements