Home > Net >  How to set new field using the field inside of document in MongoDB
How to set new field using the field inside of document in MongoDB

Time:07-25

There is a document below.

{
   price: 10000
}

And I want to add a new field using the existing field.

{
   price: 10000,
   vat: 1000, // price*0.1
}

So, I made a query for executing in the shell.
But it doesn't work. Could you give me some advice? Thank you for reading it.

db.getCollection('test').updateMany({},{$set:{'vat': "$price" * 0.1}})

$mul operator doesn't work for this case, either.

CodePudding user response:

You need to use aggregate update

db.collection.update({},
[//aggregate update
  {
    $set: {
      vat: {
        "$multiply": [ //aggregate operator
          "$price",
          0.1
        ]
      }
    }
  }
],
{
  "multi": true,
  "upsert": false
})

sample

  • Related