Mario Cares Cabezas
Mario Cares Cabezas

Reputation: 307

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

Upvotes: 16

Views: 22948

Answers (3)

nimrod serok
nimrod serok

Reputation: 16033

Since mongoDB version 3.4 you can use $reduce to sum array items:

db.collection.aggregate([
  {
    $match: {Usuario: "MarioCares"}
  },
  {
    $project: {
      suma: {
        $reduce: {
          input: "$Egresos",
          initialValue: 0,
          in: {$add: ["$$value", "$$this.Monto"]}
        }
      }
    }
  }
])

Playground example

Upvotes: 0

Aabid
Aabid

Reputation: 941

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

Upvotes: 11

JohnnyHK
JohnnyHK

Reputation: 311835

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

Upvotes: 29

Related Questions