MongoDB query to sort by the sum of specified object inside inner array?

To sort by the sum of specified object inside inner array, use $unwind, $group, and $sort in an aggregation pipeline. This approach counts occurrences of specific values within arrays and sorts documents accordingly.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $group: {
        _id: "$_id",
        total: { $sum: { $cond: {
            if: { $eq: ["$arrayField.field", value] },
            then: 1,
            else: 0
        }}},
        arrayField: { $push: "$arrayField" }
    }},
    { $sort: { total: -1 } },
    { $project: { arrayField: 1 } }
]);

Sample Data

db.demo189.insertMany([
    {
        "_id": 100,
        "List": [
            { "Value": 10 },
            { "Value": 20 },
            { "Value": 10 }
        ]
    },
    {
        "_id": 101,
        "List": [
            { "Value": 10 },
            { "Value": 10 },
            { "Value": 10 }
        ]
    }
]);
{ "acknowledged": true, "insertedIds": { "0": 100, "1": 101 } }

Example: Sort by Count of Value 10

Sort documents by the count of objects where Value equals 10 in descending order ?

db.demo189.aggregate([
    { "$unwind": "$List" },
    { "$group": {
        "_id": "$_id",
        "total": {
            "$sum": {
                "$cond": {
                    "if": { "$eq": ["$List.Value", 10] },
                    "then": 1,
                    "else": 0
                }
            }
        },
        "List": {
            "$push": {
                "Value": "$List.Value"
            }
        }
    }},
    { "$sort": { "total": -1 } },
    { "$project": {
        "List": 1
    }}
]);
{ "_id": 101, "List": [{ "Value": 10 }, { "Value": 10 }, { "Value": 10 }] }
{ "_id": 100, "List": [{ "Value": 10 }, { "Value": 20 }, { "Value": 10 }] }

How It Works

  • $unwind: Deconstructs the array to process each element individually
  • $group: Counts matching values using $cond and rebuilds the original array
  • $sort: Orders documents by the calculated total in descending order
  • $project: Returns only the List field in the final output

Conclusion

Use aggregation pipeline with $unwind and $group to count specific values in arrays, then sort by those counts. The $cond operator enables conditional counting based on field values.

Updated on: 2026-03-15T01:41:33+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements