MongoDB query to update each field of documents in collection with a formula?


To update each field of documents in collection with a formula, use MongoDB update(). Let us create a collection with documents −

> db.demo749.insertOne({"details":[{"id":1,a:10},{"id":2,a:5},{"id":3,a:20}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae6fb0a930c785c834e565")
}

Display all documents from a collection with the help of find() method −

> db.demo749.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5eae6fb0a930c785c834e565"),
   "details" : [
      {
         "id" : 1,
         "a" : 10
      },
      {
         "id" : 2,
         "a" : 5
      },
      {
         "id" : 3,
         "a" : 20
      }
   ]
}

Following is the query to update each field of documents in collection with a formula −

> db.demo749.update(
...    {
...
...    },
...    {
...       $mul: { "details.$[].a": 2/5}
...    },
...    { multi:true}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo749.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5eae6fb0a930c785c834e565"),
   "details" : [
      {
         "id" : 1,
         "a" : 4
      },
      {
         "id" : 2,
         "a" : 2
      },
      {
         "id" : 3,
         "a" : 8
      }
   ]
}

Updated on: 30-Jun-2020

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements