I’m trying to add up two amounts within an object inside an Aggregate pipeline.
Here’s my sandbox: https://mongoplayground.net/p/LIvksL-UGur
Document:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1
},
{
"product": "basketball",
"amount": 10,
"tax": 2
}
]
}
}
]
I would like the result to be:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1,
"total": 5
},
{
"product": "basketball",
"amount": 10,
"tax": 2,
"total": 12
}
]
}
}
]
Here’s what I thought would work:
db.collection.aggregate([
{
$set: {
"result.invoices": {
"total": "$result.invoices.amount + $result.invoices.tax"
}
}
}
])
The total is empty because it’s trying to add two arrays, which I understand by trying this:
db.collection.aggregate([
{
$set: {
"result.invoices": {
"total": "$result.invoices.amount"
}
}
}
])
…which gives this:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1,
"total": [
4,
10
]
},
{
"product": "basketball",
"amount": 10,
"tax": 2,
"total": [
4,
10
]
}
]
}
}
]
How do I do it the right way?
Note: I realize this is a very simple example, and I can add the calculation after getting the results. This just illustrates a more complex problem I’m trying to solve.
3
Answers
To achieve the desired result where you add amount and tax for each item in the invoices array, you need to use the $map operator within an $addFields or $set stage in your MongoDB aggregation pipeline. This operator allows you to transform each item in an array.
Here’s the modified aggregation pipeline that should work for your scenario:
Explanation:
This pipeline will add a total field to each object in the invoices array, containing the sum of amount and tax.
As
result.invoices
is an array field, you need to use$map
to iterate through the elements and use$mergeObjects
to append thetotal
field there.Mongo Playground
You can use this:
See HERE for a working example.