Increment the value of the field using $inc operator

In this example, we are updating the salary field of an employee’s document whose name is Sumit. 

Python3




db.Employee.update({"name.first": "Sumit"},
                   {$inc: {"personalDetails.salary": 3000}})


MongoDB – Field Update Operators

MongoDB provides different types of field update operators to update the values of the fields of the documents that matches the specified condition. The following table contains the field update operators:

Operator Description
$currentDate This operator is used to set the value of a field to current date, either as a Date or a Timestamp.
$inc This operator is used to increment the value of the field by the specified amount.
$min This operator is used only to update the field if the specified value is less than the existing field value
$max This operator is used only to update the field if the specified value is greater than the existing field value.
$mul This operator is used to multiply the value of the field by the specified amount.
$rename This operator is used to rename a field.
$setOnInsert This operator is used to set the value of a field if an update results in an insert of a document. It has no effect on update operations that modify existing documents.

In the following examples, we are working with:

Database: w3wiki 

Collection: Employee 

Document: two documents that contain the details of the employees in the form of field-value pairs.

Similar Reads

Updating the value of date field using $currentDate operator:

In the example, we are updating the value of joiningDate field of an employee’s document whose first name is Om....

Increment the value of the field using $inc operator:

...

Comparing values (or numbers) using $max operator:

In this example, we are updating the salary field of an employee’s document whose name is Sumit....

Comparing values (or numbers) using $min operator:

...

Multiplying the value of a field using $mul operator:

In this example, we are comparing values(or numbers) of the salary fields with the specified value, i.e., 40000. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 40000....

Renaming a field using $rename operator:

...

Inserting new fields in new documents using $setOnInsert:

In this example, we are comparing values (or numbers) of the salary fields with the specified value, i.e, 5000. Here, the specified value is less than the current value. So. $min operator updates the value of the salary field with the help of update() method to 5000....

Contact Us