To add together a subset of elements of an array, use $first along with $sum. Let us create a collection with documents −
> db.demo610.insertOne({Values:[10,20,30,40,50]});{
"acknowledged" : true, "insertedId" : ObjectId("5e9747b8f57d0dc0b182d62e")
}Display all documents from a collection with the help of find() method −
> db.demo610.find().pretty()
This will produce the following output −
{
"_id" : ObjectId("5e9747b8f57d0dc0b182d62e"),
"Values" : [
10,
20,
30,
40,
50
]
}Here is the query to add together a subset of elements of an array in MongoDB aggregation −
> 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"}}}
... ])This will produce the following output −
{ "_id" : null, "SumOfAllExcept1stValue" : 140 }