Patrick Teixeira
Patrick Teixeira

Reputation: 97

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?

Upvotes: 1

Views: 1624

Answers (1)

Takis
Takis

Reputation: 8693

Query

  • if status=PARTIALLY_REFUNDED and amount exists
  • add field amountRefundRemaining with value FIELD_B - FIELD_A

*pipeline update requires MongoDB >= 4.2

PlayMongo

update(
{"$and": 
 [{"status": {"$eq": "PARTIALLY_REFUNDED"}}, {"amount": {"$exists": true}}]},
[{"$set": 
   {"amountRefundRemaining": {"$subtract": ["$FIELD_B", "$FIELD_A"]}}}],
{"multi": true})

Upvotes: 2

Related Questions