Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Want to update inner field in a MongoDB
To update the inner field, use the below syntax −
db.yourCollectionName.update({"_id" : yourObjectId},
{$set : {"yourOuterFieldName.yourInnerFieldName" :yourValue}});
Let us first create a collection with documents −
> db.updateDocumentDemo.insertOne(
... {
...
... "StudentDetails" : {
... "StudentFirstName" : "Adam",
... "StudentLastName" : "Samith"
... },
... "StudentOtherDetails" : {
... "StudentFavouriteSubject" : "MySQL",
... "StudentScore" : 45
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd50bb32cba06f46efe9efe")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateDocumentDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd50bb32cba06f46efe9efe"),
"StudentDetails" : {
"StudentFirstName" : "Adam",
"StudentLastName" : "Samith"
},
"StudentOtherDetails" : {
"StudentFavouriteSubject" : "MySQL",
"StudentScore" : 45
}
}
Following is the query to update the document in MongoDB −
> db.updateDocumentDemo.update({"_id" : ObjectId("5cd50bb32cba06f46efe9efe")},
... {$set : {"StudentOtherDetails.StudentFavouriteSubject" :"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents once again −
> db.updateDocumentDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd50bb32cba06f46efe9efe"),
"StudentDetails" : {
"StudentFirstName" : "Adam",
"StudentLastName" : "Samith"
},
"StudentOtherDetails" : {
"StudentFavouriteSubject" : "MongoDB",
"StudentScore" : 45
}
}Advertisements