
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 Object in Array with a Specific Key in MongoDB
Let us first create a collection with documents −
>db.demo419.insertOne({"ProductInformation":[{"ProductName":"Product-1","ProductPrice":500},{"ProductName":"Product-2","ProductPrice":600}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e724762b912067e57771ae8") }
Display all documents from a collection with the help of find() method −
> db.demo419.find();
This will produce the following output −
{ "_id" : ObjectId("5e724762b912067e57771ae8"), "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductPrice" : 600 } ] }
Following is the query to update object in array with a specific key −
> db.demo419.update({'ProductInformation.ProductName' : "Product-1" }, { $set : { 'ProductInformation.$.ProductPrice' : 1250}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo419.find();
This will produce the following output −
{ "_id" : ObjectId("5e724762b912067e57771ae8"), "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 1250 }, { "ProductName" : "Product-2", "ProductPrice" : 600 } ]
Advertisements