Update salary field value with 10 percent of each employee in MongoDB


Let us first create a collection with documents −

> db.demo417.insertOne({"EmployeeName":"Chris","EmployeeSalary":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e723ebbb912067e57771ae4")
}
> db.demo417.insertOne({"EmployeeName":"Mike","EmployeeSalary":1000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e723ed7b912067e57771ae5")
}

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

> db.demo417.find();

This will produce the following output −

{ "_id" : ObjectId("5e723ebbb912067e57771ae4"), "EmployeeName" : "Chris", "EmployeeSalary" : 500 }
{ "_id" : ObjectId("5e723ed7b912067e57771ae5"), "EmployeeName" : "Mike", "EmployeeSalary" : 1000 }

Following is the query to update salary field value with 10 percent of each employee in employee collection −

> db.demo417.update({ "EmployeeName": { $in: ["Chris", "Mike"] } }, { $mul: { EmployeeSalary: 1.1 }},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

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

> db.demo417.find();

This will produce the following output −

{ "_id" : ObjectId("5e723ebbb912067e57771ae4"), "EmployeeName" : "Chris", "EmployeeSalary" : 550 }
{ "_id" : ObjectId("5e723ed7b912067e57771ae5"), "EmployeeName" : "Mike", "EmployeeSalary" : 1100 }

Updated on: 03-Apr-2020

725 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements