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 can I update and increment two fields in one command in MongoDB?
To update and increment two fields in one command in MongoDB, use the $inc operator with multiple field-value pairs in a single update operation. This allows you to increment multiple numeric fields atomically in one database call.
Syntax
db.collection.update(
{ query },
{ $inc: { field1: value1, field2: value2 } }
);
Create Sample Data
Let us first create a collection with documents ?
db.incrementDemo.insertOne({
"Value1": 10,
"Value2": 20
});
{
"acknowledged": true,
"insertedId": ObjectId("5cbdaf07de8cc557214c0e15")
}
Display all documents from the collection ?
db.incrementDemo.find().pretty();
{
"_id": ObjectId("5cbdaf07de8cc557214c0e15"),
"Value1": 10,
"Value2": 20
}
Example: Increment Two Fields
Following is the query to increment two fields in one command ?
db.incrementDemo.update(
{},
{ $inc: { Value1: 1, Value2: 1 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Let us check both fields have been incremented ?
db.incrementDemo.find().pretty();
{
"_id": ObjectId("5cbdaf07de8cc557214c0e15"),
"Value1": 11,
"Value2": 21
}
Conclusion
The $inc operator allows you to increment multiple fields simultaneously in a single atomic operation. This approach is efficient and ensures data consistency when updating multiple numeric fields.
Advertisements
