mongodbmongoosemongodb-queryrobo3t

MongoDB - Sum the field in an array


How can I get all the sum of fields in an array in Mongoose? I want to sum up all the amounts in the payments array.

DB:

[
  {
    "_id": 0,
    "name": "shoe",
    "payments": [
      {
        "type": "a",
        "amount": 10
      },
      {
        "type": "b",
        "amount": 15
      },
      {
        "type": "a",
        "amount": 15
      },
      
    ]
  },
  {
    "_id": 0,
    "name": "shirt",
    "payments": [
      {
        "type": "a",
        "amount": 5
      },
      {
        "type": "b",
        "amount": 20
      },
      
    ]
  }
]

Expected result:

{
  "amountSum": 65
}

Solution

  • There is a shorter and most likely faster solution:

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          amountSum: { $sum: { $sum: "$payments.amount" } }
        }
      }
    ])