Sum in nested document MongoDB

后端 未结 2 915
春和景丽
春和景丽 2020-12-01 08:40

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         


        
相关标签:
2条回答
  • 2020-12-01 09:05

    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" }
        }}
    ])
    
    0 讨论(0)
  • 2020-12-01 09:24

    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" }
            }
        }
    ])
    
    0 讨论(0)
提交回复
热议问题