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
$group
– Group all documents.1.1.
$sum
– Sum the value returned from 1.1.1 for theamountSum
field.1.1.1.
$reduce
– Aspayments
is an array of objects, sum all theamount
for the elements and transform the result from the array to number.Demo @ Mongo Playground
There is a shorter and most likely faster solution: