- 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
Updating Nested Embedded Documents in MongoDB?
To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us create a collection with documents −
> db.demo643.insertOne({ ... details : [ ... { ... "CountryName":"US", ... StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}] ... }, ... ... { ... "CountryName":"UK", ... StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e9c737f6c954c74be91e6e3") }
Display all documents from a collection with the help of find() method −
> db.demo643.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }
Following is the query to update nested embedded documents in MongoDB −
> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo643.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" }, { "Marks" : 78 } ] } ] }
Advertisements