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 value in a MongoDB nested object?
To increment a value in a MongoDB nested object, use the $inc operator combined with the $ positional operator to target the specific nested element and increment its numeric value.
Syntax
db.collection.update(
{"nestedArray.field": "matchValue"},
{ $inc: { "nestedArray.$.fieldToIncrement": incrementValue } }
);
Create Sample Data
Let us create a collection with a document containing nested array objects ?
db.incrementValueDemo.insertOne({
"StudentName": "Larry",
"StudentCountryName": "US",
"StudentDetails": [
{
"StudentSubjectName": "Math",
"StudentMathMarks": 79
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5c986ca0330fd0aa0d2fe4a2")
}
Display Current Document
db.incrementValueDemo.find().pretty();
{
"_id": ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName": "Larry",
"StudentCountryName": "US",
"StudentDetails": [
{
"StudentSubjectName": "Math",
"StudentMathMarks": 79
}
]
}
Increment Nested Value
Increment the Math marks by 1 using $inc operator ?
db.incrementValueDemo.update(
{"StudentDetails.StudentSubjectName": "Math"},
{ $inc: { "StudentDetails.$.StudentMathMarks": 1 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.incrementValueDemo.find().pretty();
{
"_id": ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName": "Larry",
"StudentCountryName": "US",
"StudentDetails": [
{
"StudentSubjectName": "Math",
"StudentMathMarks": 80
}
]
}
Key Points
- The
$positional operator identifies the first matching array element. -
$inccan increment by positive or negative values (use negative to decrement). - The field being incremented must contain a numeric value.
Conclusion
Use $inc with the $ positional operator to increment numeric values in nested objects. The query condition identifies the array element, and $inc performs the increment operation on the specified nested field.
Advertisements
