- 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 nested document
Let us create a collection with documents −
> db.demo595.insertOne( { "Information": [ { "_id": new ObjectId(), Name:"Chris" }, { _id:new ObjectId(), Name:"Robert" } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5e93369cfd2d90c177b5bce4") }
Display all documents from a collection with the help of find() method −
> db.demo595.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e93369cfd2d90c177b5bce4"), "Information" : [ { "_id" : ObjectId("5e93369cfd2d90c177b5bce2"), "Name" : "Chris" }, { "_id" : ObjectId("5e93369cfd2d90c177b5bce3"), "Name" : "Robert" } ] }
Following is the query to update nested document −
>db.demo595.update({"Information._id":ObjectId("5e93369cfd2d90c177b5bce2")}, {$set:{"Info rmation.$.Name":"David Miller"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo595.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e93369cfd2d90c177b5bce4"), "Information" : [ { "_id" : ObjectId("5e93369cfd2d90c177b5bce2"), "Name" : "David Miller" }, { "_id" : ObjectId("5e93369cfd2d90c177b5bce3"), "Name" : "Robert" } ] }
Advertisements