- 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 document in MongoDB
To update the nested document, use $set. Let us create a collection with documents −
> db.demo315.insertOne({ _id :101, ... details: [ ... {Name: 'Chris', subjects: [{id:1001, SubjectName:"MySQL"}]} ... ] ... } ...) { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo315.find().pretty();
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "Chris", "subjects" : [ { "id" : 1001, "SubjectName" : "MySQL" } ] } ] }
Following is the query to update the nested document in MongoDB −
> db.demo315.update ({_id:101}, { '$set': {"details.0.subjects.1.id" :1004} }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo315.find().pretty();
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "Chris", "subjects" : [ { "id" : 1001, "SubjectName" : "MySQL" }, { "id" : 1004 } ] } ] }
Advertisements