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
Increment only a single value in MongoDB document?
To increment only a single value in a MongoDB document, use the $inc operator with the update() method. The $inc operator increases the value of a field by the specified amount.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $inc: { "fieldToIncrement": incrementValue } }
);
Create Sample Data
Let us create a collection with documents containing Score values ?
db.demo698.insertMany([
{ Score: 78 },
{ Score: 56 },
{ Score: 65 },
{ Score: 88 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea6d8a4551299a9f98c9398"),
ObjectId("5ea6d8a7551299a9f98c9399"),
ObjectId("5ea6d8aa551299a9f98c939a"),
ObjectId("5ea6d8b0551299a9f98c939b")
]
}
Display all documents from the collection ?
db.demo698.find();
{ "_id": ObjectId("5ea6d8a4551299a9f98c9398"), "Score": 78 }
{ "_id": ObjectId("5ea6d8a7551299a9f98c9399"), "Score": 56 }
{ "_id": ObjectId("5ea6d8aa551299a9f98c939a"), "Score": 65 }
{ "_id": ObjectId("5ea6d8b0551299a9f98c939b"), "Score": 88 }
Example: Increment Single Value
Increment the Score field by 12 for a specific document ?
db.demo698.update(
{ _id: ObjectId("5ea6d8b0551299a9f98c939b") },
{ $inc: { Score: 12 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the increment operation ?
db.demo698.find();
{ "_id": ObjectId("5ea6d8a4551299a9f98c9398"), "Score": 78 }
{ "_id": ObjectId("5ea6d8a7551299a9f98c9399"), "Score": 56 }
{ "_id": ObjectId("5ea6d8aa551299a9f98c939a"), "Score": 65 }
{ "_id": ObjectId("5ea6d8b0551299a9f98c939b"), "Score": 100 }
Key Points
- The
$incoperator works with numeric values only. - Use a positive value to increment, negative value to decrement.
- Only the matched document gets updated, other documents remain unchanged.
Conclusion
The $inc operator provides an efficient way to increment specific numeric fields in MongoDB documents. It atomically updates only the target field without affecting other document properties.
Advertisements
