
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update Array of Subdocuments in MongoDB
To update, use update() along with $set. Let us create a collection with documents −
>db.demo134.insertOne({"EmployeeId":101,"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeAge":27},{"EmployeeName":"Bob","EmployeeAge":28}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b2f68e7f832db1a7f7c") } >db.demo134.insertOne({"EmployeeId":102,"EmployeeDetails":[{"EmployeeName":"David","EmployeeAge":24},{"EmployeeName":"Carol","EmployeeAge":29}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b4468e7f832db1a7f7d") }
Display all documents from a collection with the help of find() method −
> db.demo134.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Chris", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }
Following is the query to update array of subdocuments in MongoDB −
> db.demo134.update( ... { ... "EmployeeId":101, ... "EmployeeDetails.EmployeeName":"Chris" ... }, ... { ... $set: { ... "EmployeeDetails.$.EmployeeName" : "Robert" ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo134.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Robert", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }
Advertisements