How to add together a subset of elements of an array in MongoDB aggregation?

To add together a subset of elements of an array in MongoDB aggregation, use the $slice operator combined with $sum to select and sum specific array elements based on position or range.

Syntax

db.collection.aggregate([
    {
        $project: {
            subsetSum: {
                $sum: {
                    $slice: ["$arrayField", startIndex, numberOfElements]
                }
            }
        }
    }
])

Sample Data

db.demo610.insertOne({
    Values: [10, 20, 30, 40, 50]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e9747b8f57d0dc0b182d62e")
}
db.demo610.find().pretty();
{
    "_id": ObjectId("5e9747b8f57d0dc0b182d62e"),
    "Values": [10, 20, 30, 40, 50]
}

Method 1: Using $slice (Recommended)

Sum all elements except the first one using $slice ?

db.demo610.aggregate([
    {
        $project: {
            SumOfAllExcept1stValue: {
                $sum: {
                    $slice: ["$Values", 1, 4]
                }
            }
        }
    }
]);
{ "_id": ObjectId("5e9747b8f57d0dc0b182d62e"), "SumOfAllExcept1stValue": 140 }

Method 2: Using $unwind and $group

Alternative approach using array unwinding and grouping ?

db.demo610.aggregate([
    { $unwind: "$Values" },
    {
        $group: {
            "_id": "$_id",
            "1st": { $first: "$Values" },
            "All": { $sum: "$Values" }
        }
    },
    {
        $project: {
            "_id": "$_id",
            "SumOfAllMinus1": { $subtract: ["$All", "$1st"] }
        }
    },
    {
        $group: {
            "_id": null,
            "SumOfAllExcept1stValue": { $sum: "$SumOfAllMinus1" }
        }
    }
]);
{ "_id": null, "SumOfAllExcept1stValue": 140 }

Key Points

  • $slice method is more efficient for simple subset operations
  • $unwind approach provides more flexibility for complex array processing
  • Use $slice parameters: [array, startIndex, count] to define the subset

Conclusion

Use $slice with $sum for efficient subset array summation. For complex processing, combine $unwind, $group, and arithmetic operators to achieve the desired subset calculations.

Updated on: 2026-03-15T03:49:57+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements