MongoDB – Increment Operator ( $inc )

MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value.

You can also use this operator in embedded/nested documents. You can use this operator in methods like update(), updateOne() etc. according to your requirements.

  • This operator accepts positive and negative values.
  • If the given field does not exist, then this operator will create field and set the value of that field.
  • This operator will generate an error, if you use this operator with null value field.
  • It is an atomic operation in a single document.

Syntax:

{ $inc: { field1: amount1, field2: amount2, ... } }

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.



Increment the value of the field using $inc operator:

In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})

chevron_right


Increment the value of the field in the array using $inc operator:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})

chevron_right


Increment the value of the field in embedded document using $inc operator:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.