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

MongoDBDatabaseBig Data Analytics

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
      }
   ]
}
raja
Published on 30-Jun-2020 11:41:03
Advertisements