I have some data like that:
{id: 1, myData: [[2, 0, 0], [0, 0, 0, 3, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0]]}
{id: 2, myData: [[11, 0, 0], [0, 0, 0], [1, 1, 2]]}
I need to sum all numbers in each array to unique total vaule.
Desired output:
[{id:1, sumData: 8}
{id:2, sumData: 15}]
I tried to fix through group aggregation, but it is not working:
{
$group:
{
_id: "$id",
myDataSum: {
$sum: "$myData",
},
},
}
How could I get the sum for all fields?
>Solution :
One option is to use $sum inside a $reduce:
db.collection.aggregate([
{$project: {
sumData: {$reduce: {
input: "$myData",
initialValue: 0,
in: {$add: [
"$$value",
{$sum: "$$this"}
]}
}}
}}
])
See how it works on the playground example