- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 database?
To update child objects, use $set in MongoDB. Let us first create a collection with documents −
>db.demo21.insertOne({"StudentId":"STU-101","StudentDetails":{"StudentName":"Chris","StudentAge":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e14be8922d07d3b95082e6f") }
Display all documents from a collection with the help of find() method −
> db.demo21.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e14be8922d07d3b95082e6f"), "StudentId" : "STU-101", "StudentDetails" : { "StudentName" : "Chris", "StudentAge" : 21 } }
Following is the query to update child objects in MongoDB −
> db.demo21.update({"StudentId":'STU-101'},{$set:{'StudentDetails.StudentName':'Robert'}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo21.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e14be8922d07d3b95082e6f"), "StudentId" : "STU-101", "StudentDetails" : { "StudentName" : "Robert", "StudentAge" : 21 } }
Advertisements