简体   繁体   中英

MongoDB UpdateMany

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?

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM