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
Updating nested document in MongoDB
To update nested documents in MongoDB, use the $set operator with dot notation to specify the exact path to the field you want to modify. This allows you to update deeply nested fields without affecting other parts of the document.
Syntax
db.collection.update(
{ "matchField": "value" },
{ $set: { "path.to.nested.field": "newValue" } }
);
Sample Data
Let us create a collection with a nested document ?
db.demo315.insertOne({
_id: 101,
details: [
{
Name: "Chris",
subjects: [
{ id: 1001, SubjectName: "MySQL" }
]
}
]
});
{ "acknowledged": true, "insertedId": 101 }
Display the document to verify the structure ?
db.demo315.find().pretty();
{
"_id": 101,
"details": [
{
"Name": "Chris",
"subjects": [
{
"id": 1001,
"SubjectName": "MySQL"
}
]
}
]
}
Example: Update Nested Array Element
Add a new subject at index 1 in the subjects array ?
db.demo315.update(
{ _id: 101 },
{ $set: { "details.0.subjects.1.id": 1004 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo315.find().pretty();
{
"_id": 101,
"details": [
{
"Name": "Chris",
"subjects": [
{
"id": 1001,
"SubjectName": "MySQL"
},
{
"id": 1004
}
]
}
]
}
Key Points
- Use dot notation to specify the path:
details.0.subjects.1.id - Array indices are zero-based (0 = first element, 1 = second element)
- The
$setoperator creates the field if it doesn't exist
Conclusion
MongoDB's $set operator with dot notation provides precise control over nested document updates. Use array indices and field names to target specific nested elements efficiently.
Advertisements
