I\'m trying to sum some values in an array of documents, with no luck.
This is the Document
db.Cuentas.find().pretty()
{
\"Agno\": \"2013
As Sammaye indicated, you need to $unwind the Egresos
array to duplicate the matched doc per array element so you can $sum
over each element:
db.Cuentas.aggregate([
{$match: {"Usuario": "MarioCares"} },
{$unwind: '$Egresos'},
{$group: {
_id: null,
"suma": {$sum: "$Egresos.Monto" }
}}
])
You can do also by this way. don't need to group just project your fields.
db.Cuentas.aggregate([
{ $match: { "Usuario": "MarioCares" } },
{
$project: {
'MontoSum': { $sum: "$Egresos.Monto" }
}
}
])