Sum in nested document MongoDB

2019-01-08 23:47发布

问题:

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

回答1:

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" }
    }}
])


回答2:

I know it's a bit late but you can do also by this way. don't need to group just project your fields.

db.Cuentas.aggregate([
    { $match: { "Usuario": "MarioCares" } },
    {
        $poject: {
            'MontoSum': { $sum: "$Egresos.Monto" }
        }
    }
])