Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum in nested document MongoDB

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",
    "Egresos": [
        {
            "Fecha": "28-01-2013",
            "Monto": 150000,
            "Detalle": "Pago Nokia Lumia a @josellop"
        },
        {
            "Fecha": "29-01-2013",
            "Monto": 4000,
            "Detalle": "Cine, Pelicula fome"
        }
    ],
    "Ingresos": [],
    "Mes": "Enero",
    "Monto": 450000,
    "Usuario": "MarioCares"
    "_id": ObjectId(....)
}

So, i need the sum of all the "Monto" in "Egresos" for the "Usuario": "MarioCares". In this example 154000

Using aggregation i use this:

db.Cuentas.aggregate(
    [
        { $match: {"Usuario": "MarioCares"} },
        { $group: 
            {
                _id: null,
                "suma": { $sum: "$Egresos.Monto" }
            }
        }
    ]
)

But i always get

{ "result" : [{ "_id" : null, "suma" : 0 }], "ok" : 1 }

What am i doing wrong ?

P.D. already see this and this

like image 213
Mario Cares Cabezas Avatar asked Jan 28 '13 20:01

Mario Cares Cabezas


2 Answers

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" }
    }}
])
like image 166
JohnnyHK Avatar answered Sep 28 '22 00:09

JohnnyHK


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" }
        }
    }
])
like image 32
Aabid Avatar answered Sep 27 '22 23:09

Aabid