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
Want to update inner field in a MongoDB
To update an inner field in MongoDB, use the $set operator with dot notation to target the nested field within a document. This allows you to modify specific fields inside embedded documents without affecting other fields.
Syntax
db.collectionName.update(
{"_id": ObjectId},
{$set: {"outerField.innerField": newValue}}
);
Sample Data
Let us create a collection with a document containing nested fields ?
db.updateDocumentDemo.insertOne({
"StudentDetails": {
"StudentFirstName": "Adam",
"StudentLastName": "Samith"
},
"StudentOtherDetails": {
"StudentFavouriteSubject": "MySQL",
"StudentScore": 45
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd50bb32cba06f46efe9efe")
}
View Current Document
db.updateDocumentDemo.find().pretty();
{
"_id": ObjectId("5cd50bb32cba06f46efe9efe"),
"StudentDetails": {
"StudentFirstName": "Adam",
"StudentLastName": "Samith"
},
"StudentOtherDetails": {
"StudentFavouriteSubject": "MySQL",
"StudentScore": 45
}
}
Update Inner Field
Update the "StudentFavouriteSubject" field from "MySQL" to "MongoDB" ?
db.updateDocumentDemo.update(
{"_id": ObjectId("5cd50bb32cba06f46efe9efe")},
{$set: {"StudentOtherDetails.StudentFavouriteSubject": "MongoDB"}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.updateDocumentDemo.find().pretty();
{
"_id": ObjectId("5cd50bb32cba06f46efe9efe"),
"StudentDetails": {
"StudentFirstName": "Adam",
"StudentLastName": "Samith"
},
"StudentOtherDetails": {
"StudentFavouriteSubject": "MongoDB",
"StudentScore": 45
}
}
Conclusion
Use dot notation with $set to update nested fields in MongoDB documents. This approach modifies only the specified inner field while preserving all other document structure and values.
Advertisements
