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
MongoDB query to update the nested document?
To update a nested document in MongoDB, use the update() method with dot notation to specify the path to the nested field. This allows you to modify deeply embedded values without affecting the parent document structure.
Syntax
db.collection.update(
{ "filterField": "value" },
{ $set: { "parentField.nestedField.targetField": "newValue" } }
);
Sample Data
Let us create a collection with a nested document structure ?
db.demo607.insertOne({
id: 1,
"Info1": {
"Name": "Chris",
"Age": 21,
"Info2": {
"SubjectName": "MongoDB",
"Marks": 89
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e9742a5f57d0dc0b182d62a")
}
Example: Update Nested Field
Display the current document ?
db.demo607.find();
{
"_id": ObjectId("5e9742a5f57d0dc0b182d62a"),
"id": 1,
"Info1": {
"Name": "Chris",
"Age": 21,
"Info2": {
"SubjectName": "MongoDB",
"Marks": 89
}
}
}
Update the nested Marks field from 89 to 90 ?
db.demo607.update(
{ id: 1 },
{ $set: { "Info1.Info2.Marks": 90 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.demo607.find().pretty();
{
"_id": ObjectId("5e9742a5f57d0dc0b182d62a"),
"id": 1,
"Info1": {
"Name": "Chris",
"Age": 21,
"Info2": {
"SubjectName": "MongoDB",
"Marks": 90
}
}
}
Key Points
- Use dot notation to traverse nested document levels:
"parentField.childField.targetField" - The
$setoperator updates only the specified field without modifying the entire document structure - Multiple nested levels can be accessed by chaining field names with dots
Conclusion
MongoDB's dot notation with the $set operator provides a clean way to update nested document fields. This approach preserves the document structure while precisely targeting the field that needs modification.
Advertisements
