Can you guys help me with this problem?
Example:
Data:
{
_id: "63f69650e820990f82dca60b",
...,
transactions: [
{
...,
fee: "100",
...
},
{
...,
fee: "200",
...
}
]
}
I want to add a total_fee field to calculate total fee of all the transactions in a document.
I tried using
$addfields: {
total_fee: {
$sum: {$toInt: "$transactions.fee"}
}
}
But mongo return error about can’t convert array to int
2
Answers
When you specify
"$transactions.fee"
, it resolves to an array of strings.$toInt
doesn’t accept an array.You use
$reduce
to iterate through the array and convert each string to integer, before adding.Demo
Using
$reduce
is an overkill in my opinion.$map
should be simpler and is certainly faster:Of course, the proper solution is to store numeric values as number rather than strings.