So I have a mongodb document
{
"id": 1,
"balance": 10,
"transactions": [
{
"balance": 10,
"transaction_amount": 10
}
]
}
I want to add another object inside of transactions array and that object uses previous balance and adds the newer value. For eg, transaction amount is 20 the document should be updated in this way
{
"id": 1,
"balance": 30,
"transactions": [
{
"balance": 10,
"transaction_amount": 10
},
{
"balance": 30,
"transaction_amount": 20
}
]
}
Now if I want to add one more document in transactions array with transaction_amount as 5 the resultant document becomes
{
"id": 1,
"balance": 35,
"transactions": [
{
"balance": 10,
"transaction_amount": 10
},
{
"balance": 30,
"transaction_amount": 20
},
{
"balance": 35,
"transaction_amount": 5
}
]
}
Is there any way to do this using aggregation pipeline
CodePudding user response:
Simply use $add
and $concatArrays
to wrangle the data
db.collection.update({
id: 1
},
[
{
"$addFields": {
"txnAmt": <amount you want>
}
},
{
$addFields: {
balance: {
$add: [
"$balance",
"$txnAmt"
]
}
}
},
{
"$addFields": {
"transactions": {
"$concatArrays": [
"$transactions",
[
{
balance: "$balance",
transaction_amount: "$txnAmt"
}
]
]
}
}
},
{
"$unset": "txnAmt"
}
],
{
multi: true
})
Here is the Mongo playground for your reference.