How to sum the value of a key across all documents in a MongoDB collection

In this case, aggregation is much simpler and much more efficient than mapReduce:

db.collection.aggregate({
    $group: {
        _id: '',
        subida: { $sum: '$subida' }
    }
 }, {
    $project: {
        _id: 0,
        subida: '$subida'
    }
})
  1. use $group with $sum to calculate sum
  2. use projection’s $project operator to remove id key required by $group operator

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)