![]() |
VOOZH | about |
The $inc operator in MongoDBdatabase atomically increments or decrements numeric fields by a specified value, making it ideal for counters, scores, and inventory updates while ensuring data consistency.
{ $inc: { field1: amount1, field2: amount2, ... } }We'll use a sample database called GeeksforGeeks, which contains a contributor collection.
Updating the fields of a contributor's document whose name is Lucas by incrementing the value of the publisharticles field by 10 and decreasing the value of the salary field by 100.
db.contributor.updateOne({ name: "Lucas" }, { $inc: { publisharticles: 10, salary: -100 } })Output:
Update the value of a nested field a in the array points, for a specific document where the name is "Sophia" and the points._id is "g_1"
db.contributor.updateOne({name: "Sophia" , "points._id" : "g_1"}, {$inc: {"points.$.a":10}})Output:
Increment the value of the rank field in an embedded document personal for a document where the name is "Oliver".
db.contributor.updateOne({name: "Oliver"}, {$inc: {"personal.rank": 2}})Output:
These points highlight how $inc handles field creation, errors, and atomic updates to maintain data consistency.