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 a property value of an element in array object with MongoDB
To increment a property value of an element in a MongoDB array, use the $inc operator combined with the $ positional operator. The $ operator identifies the matched array element, while $inc increases the specified field by a given value.
Syntax
db.collection.update(
{ "arrayField.property": "matchValue" },
{ $inc: { "arrayField.$.targetProperty": incrementValue } }
);
Sample Data
Let us create a collection with student details ?
db.demo97.insertOne({
"Details": [
{
"Name": "Chris",
"Marks": 45
},
{
"Name": "Bob",
"Marks": 88
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2d6d24b8903cdd865577af")
}
Display the current document ?
db.demo97.find();
{
"_id": ObjectId("5e2d6d24b8903cdd865577af"),
"Details": [
{ "Name": "Chris", "Marks": 45 },
{ "Name": "Bob", "Marks": 88 }
]
}
Example: Increment Bob's Marks by 10
db.demo97.update(
{ "Details.Name": "Bob" },
{ $inc: { "Details.$.Marks": 10 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo97.find();
{
"_id": ObjectId("5e2d6d24b8903cdd865577af"),
"Details": [
{ "Name": "Chris", "Marks": 45 },
{ "Name": "Bob", "Marks": 98 }
]
}
Key Points
- The
$positional operator targets the first matching array element -
$inccan increment by positive or negative values (use negative to decrement) - The target field must be a numeric type for
$incto work
Conclusion
Use $inc with the $ positional operator to increment numeric properties within array objects. This approach efficiently updates specific array elements without affecting other elements in the array.
Advertisements
