Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Update salary field value with 10 percent of each employee in MongoDB
To update salary field values with a 10 percent increase for each employee in MongoDB, use the $mul operator with a multiplier of 1.1. This operator multiplies the existing field value by the specified number.
Syntax
db.collection.update(
{ query },
{ $mul: { fieldName: multiplier } },
{ multi: true }
);
Create Sample Data
Let us first create a collection with employee documents ?
db.demo417.insertMany([
{"EmployeeName": "Chris", "EmployeeSalary": 500},
{"EmployeeName": "Mike", "EmployeeSalary": 1000}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e723ebbb912067e57771ae4"),
ObjectId("5e723ed7b912067e57771ae5")
]
}
Display all documents from the collection ?
db.demo417.find();
{ "_id": ObjectId("5e723ebbb912067e57771ae4"), "EmployeeName": "Chris", "EmployeeSalary": 500 }
{ "_id": ObjectId("5e723ed7b912067e57771ae5"), "EmployeeName": "Mike", "EmployeeSalary": 1000 }
Update Salary with 10% Increase
Use the $mul operator to increase all employee salaries by 10% ?
db.demo417.update(
{ "EmployeeName": { $in: ["Chris", "Mike"] } },
{ $mul: { EmployeeSalary: 1.1 } },
{ multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Results
Display the updated documents to confirm the salary increase ?
db.demo417.find();
{ "_id": ObjectId("5e723ebbb912067e57771ae4"), "EmployeeName": "Chris", "EmployeeSalary": 550 }
{ "_id": ObjectId("5e723ed7b912067e57771ae5"), "EmployeeName": "Mike", "EmployeeSalary": 1100 }
Key Points
- The
$muloperator multiplies the field value by the specified number (1.1 = 10% increase). - Use
{multi: true}to update multiple documents that match the query. - For all employees, you can use an empty query:
{}instead of specific names.
Conclusion
The $mul operator efficiently increases salaries by multiplying existing values. Using multiplier 1.1 adds exactly 10% to each employee's current salary, making it ideal for percentage-based updates.
Advertisements
