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 } ]

Updated on: 03-Apr-2020

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements