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
How to increment a field in MongoDB?
To increment a field in MongoDB, use the $inc operator with the update() method. The $inc operator increases the numeric value of a field by a specified amount.
Syntax
db.collection.update(
{ "query": "criteria" },
{ $inc: { "fieldName": incrementValue } }
);
Sample Data
Let us create a collection with player scores ?
db.incrementDemo.insertMany([
{ "PlayerScore": 100 },
{ "PlayerScore": 290 },
{ "PlayerScore": 560 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc81cdd8f9e6ff3eb0ce44e"),
ObjectId("5cc81ce28f9e6ff3eb0ce44f"),
ObjectId("5cc81ce68f9e6ff3eb0ce450")
]
}
Display all documents from the collection ?
db.incrementDemo.find().pretty();
{ "_id": ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore": 100 }
{ "_id": ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore": 290 }
{ "_id": ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore": 560 }
Example: Increment Player Score
Increment the PlayerScore of the second document by 10 ?
db.incrementDemo.update(
{ "_id": ObjectId("5cc81ce28f9e6ff3eb0ce44f") },
{ $inc: { "PlayerScore": 10 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify the result ?
db.incrementDemo.find().pretty();
{ "_id": ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore": 100 }
{ "_id": ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore": 300 }
{ "_id": ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore": 560 }
Key Points
- The
$incoperator only works with numeric values (integers, floats). - Use negative values to decrement:
{ $inc: { "field": -5 } } - If the field doesn't exist,
$inccreates it with the increment value.
Conclusion
The $inc operator provides an efficient way to increment numeric fields in MongoDB. It can both increase and decrease values, and automatically creates the field if it doesn't exist.
Advertisements
