0

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
}

2 Answers 2

2

There is a shorter and most likely faster solution:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      amountSum: { $sum: { $sum: "$payments.amount" } }
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

1
  1. $group - Group all documents.

    1.1. $sum - Sum the value returned from 1.1.1 for the amountSum field.

    1.1.1. $reduce - As payments is an array of objects, sum all the amount for the elements and transform the result from the array to number.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      amountSum: {
        $sum: {
          $reduce: {
            input: "$payments",
            initialValue: 0,
            in: {
              $sum: [
                "$$value",
                "$$this.amount"
              ]
            }
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.