- 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
MongoDB query to update the nested document?
To update the nested document, use update() and within that, use dot notation. Let us create a collection with documents −
> db.demo607.insertOne( ... { ... id:1, ... "Info1" : { ... "Name" : "Chris", ... "Age" : 21, ... ... "Info2" : { ... "SubjectName" : "MongoDB", ... "Marks" : 89 ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9742a5f57d0dc0b182d62a") }
Display all documents from a collection with the help of find() method −
> db.demo607.find();
This will produce the following output −
{ "_id" : ObjectId("5e9742a5f57d0dc0b182d62a"), "id" : 1, "Info1" : { "Name" : "Chris", "Age" : 21, "Info2" : { "SubjectName" : "MongoDB", "Marks" : 89 } } }
Following is the query to update nested document −
> db.demo607.update({id:1},{$set:{"Info1.Info2.Marks":90}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo607.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e9742a5f57d0dc0b182d62a"), "id" : 1, "Info1" : { "Name" : "Chris", "Age" : 21, "Info2" : { "SubjectName" : "MongoDB", "Marks" : 90 } } }
Advertisements