Home > Software design >  Calculate values dynamically when updating a document in mongosh
Calculate values dynamically when updating a document in mongosh

Time:10-26

I'm trying to update some documents using the mongo shell in mongodb compass. I'm using the updateMany function to do so. I want to calculate some values when updating the field. for example

This is an example document

Account

  capital: 100,
  deposit: 0

I want to apply something like this

db.account.updateMany({}, {$set: {deposit: this.deposit   this.capital}})

but this is not working

CodePudding user response:

You want to use the aggregated pipeline updates syntax to achieve this, This is the only way to use existing document data within an update as a value. The syntax (in your case) remains quite similar, like so:

db.account.updateMany(
{},
[
  {
    $set: {
      deposit: {
        $add: [
          "$deposit",
          "$capital"
        ]
      }
    }
  }
])

Mongo Playground

  • Related