I need to update various fields in mongo creating a new field. Example:
db.paymentTransaction.updateOne(
{status: "PARTIALLY_REFUNDED"},
{amount: EXISTS}
{
$set: {
"amountRefundRemaining": {
FIELD_B - FIELD_A
}
}
}
)
I need to create the field amountRefundRemaining. But I need to fill this new field with the result of the substraction of Field_B minus Field_A. But I only need to do this where status=PARTIALLY_REFUNDED and amount exists
Im using mongoDB 4.4. Any ideias?
CodePudding user response:
Query
- if
status=PARTIALLY_REFUNDED
andamount exists
- add field
amountRefundRemaining
with valueFIELD_B - FIELD_A
*pipeline update requires MongoDB >= 4.2
db.collection.update({
"status": "PARTIALLY_REFUNDED",
"amount": {"$exists": true}},
[
{
"$set": {
"amountRefundRemaining": {
"$subtract": [
"$FIELD_B",
"$FIELD_A"
]
}
}
}
],
{"multi": true})