简体   繁体   中英

MongoDB Aggregation Sum on Objects in Array make it work

{ "id": 1, "stats": [ { "number": 100, "year": 2014 }, { "number": 200, "year": 2015 } ] }

I want to sum the number with the arrays using aggregate i have tired but not getting it and should give me 300

db.test.aggregate([
  {$project: 
    {totalSum: 
      {$reduce: 
        {input:'$stats', initialValue:0, in: {$sum: '$stats.number'}}
      }
    }
  }
  ])

You basically just want to add a field which will contain the sum (you can use $addFields or $projects) and then u want to reduce the given array to a single value which is exactly what the $reduce stage does. ( https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/ )

The reduce stage requires 3 parameters: 'input' which requires a reference to the array, 'initialValue' which you can think of as an accumulator variable, and for the last parameter the 'in' requires what exactly you want to store in that accumulator variable. In this case you wanted to sum up '$stats.number'

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM