
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
MongoDB Query to Update a Specific Document from a Collection
To update, use $set along with UPDATE. Let us create a collection with documents −
>db.demo135.insertOne({"Details":[{"EmployeeId":101,"EmployeeName":"Chris","EmployeeSalary":45000},{"EmployeeId":102,"EmployeeName":"Chris","EmployeeSalary":45000}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31a5ddfdf09dd6d085399c") }
Display all documents from a collection with the help of find() method −
> db.demo135.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"), "Details" : [ { "EmployeeId" : 101, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 }, { "EmployeeId" : 102, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 } ] }
Following is the query to update second document −
> db.demo135.update( ... { ... ... "Details.EmployeeId":102, ... ... }, ... { ... $set: { ... "Details.$.EmployeeName" : "John Doe" ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo135.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"), "Details" : [ { "EmployeeId" : 101, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 }, { "EmployeeId" : 102, "EmployeeName" : "John Doe", "EmployeeSalary" : 45000 } ] }
Advertisements