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
How can I update child objects in MongoDB?
To update child objects, use $set operator. Let us first create a collection with document −
>db.updateChildObjectsDemo.insertOne({"StudentName":"Chris","StudentOtherDetails":{"StudentSubject":"MongoDB","StudentCountryName":"AUS"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce964e078f00858fb12e91f")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateChildObjectsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce964e078f00858fb12e91f"),
"StudentName" : "Chris",
"StudentOtherDetails" : {
"StudentSubject" : "MongoDB",
"StudentCountryName" : "AUS"
}
}
Following is the query to update child objects in MongoDB −
> db.updateChildObjectsDemo.update({"StudentName" : "Chris"},{$set:{"StudentOtherDetails.StudentCountryName":"UK"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.updateChildObjectsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce964e078f00858fb12e91f"),
"StudentName" : "Chris",
"StudentOtherDetails" : {
"StudentSubject" : "MongoDB",
"StudentCountryName" : "UK"
}
}Advertisements