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 field in MongoDB document which is embedded?
To increment a field in a MongoDB document that is embedded within nested objects, use the $inc operator with dot notation to specify the path to the embedded field.
Syntax
db.collection.update(
{ "query": "condition" },
{ $inc: { "parent.child.field": incrementValue } }
);
Sample Data
Let's create a document with embedded StudentScores inside StudentDetails:
db.embeddedValueIncrementDemo.insertOne({
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd2b670345990cee87fd896")
}
Example: Increment Embedded Field
Let's increment the StudentMongoDBScore by 20 points using dot notation:
db.embeddedValueIncrementDemo.update(
{ _id: ObjectId("5cd2b670345990cee87fd896") },
{ $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.embeddedValueIncrementDemo.find().pretty();
{
"_id": ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 98
}
}
}
Key Points
- Use dot notation to navigate through nested objects:
"parent.child.field" - The
$incoperator can increment by positive or negative values - If the field doesn't exist,
$inccreates it with the increment value
Conclusion
Use dot notation with the $inc operator to increment embedded fields in MongoDB. The path "StudentDetails.StudentScores.StudentMongoDBScore" navigates through the nested structure to modify the target field efficiently.
Advertisements
