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 child objects in MongoDB database?
To update child objects in MongoDB, use the $set operator with dot notation to target specific fields within nested documents. This allows you to modify individual properties of embedded objects without affecting other fields.
Syntax
db.collection.update(
{ "matchField": "value" },
{ $set: { "parentObject.childField": "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.demo21.insertOne({
"StudentId": "STU-101",
"StudentDetails": {
"StudentName": "Chris",
"StudentAge": 21
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e14be8922d07d3b95082e6f")
}
Display the document to verify the initial data ?
db.demo21.find().pretty();
{
"_id": ObjectId("5e14be8922d07d3b95082e6f"),
"StudentId": "STU-101",
"StudentDetails": {
"StudentName": "Chris",
"StudentAge": 21
}
}
Example: Update Child Object Field
Update the StudentName field within the nested StudentDetails object ?
db.demo21.update(
{ "StudentId": "STU-101" },
{ $set: { "StudentDetails.StudentName": "Robert" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.demo21.find().pretty();
{
"_id": ObjectId("5e14be8922d07d3b95082e6f"),
"StudentId": "STU-101",
"StudentDetails": {
"StudentName": "Robert",
"StudentAge": 21
}
}
Key Points
- Use dot notation with
$setto target nested fields:"parent.child" - Only the specified child field is updated; other fields remain unchanged
- The operation preserves the overall document structure
Conclusion
Use $set with dot notation to update specific fields in child objects. This approach allows precise modifications to nested documents while preserving other embedded fields and the document structure.
Advertisements
