Home > Back-end >  MongoDB UpdateMany
MongoDB UpdateMany

Time:11-11

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 and amount exists
  • add field amountRefundRemaining with value FIELD_B - FIELD_A

*pipeline update requires MongoDB >= 4.2

Test code here

db.collection.update({
  "status": "PARTIALLY_REFUNDED",
  "amount": {"$exists": true}},
[
  {
    "$set": {
      "amountRefundRemaining": {
        "$subtract": [
          "$FIELD_B",
          "$FIELD_A"
        ]
      }
    }
  }
],
{"multi": true})
  • Related