In MongoDB how do you use $set to update a nested value/embedded document?

MongoDBDatabaseBig Data Analytics

The syntax is as follows for this −

db.yourCollectionName.update({ }, { $set: { "yourOuterFieldName.yourInnerFieldName": "yourValue" } });

To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.updateNestedValueDemo.insertOne({"CustomerName":"Chris",
   ... "CustomerDetails":{"CustomerAge":25,"CustomerCompanyName":"Google","CustomerCityName":"US"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fccc4d3c9d04998abf015")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.updateNestedValueDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
   "CustomerName" : "Chris",
   "CustomerDetails" : {
      "CustomerAge" : 25,
      "CustomerCompanyName" : "Google",
      "CustomerCityName" : "US"
   }
}

Here is the query to use $set to update a nested value/embedded document −

> db.updateNestedValueDemo.update({ }, { $set: { "CustomerDetails.CustomerCompanyName": "Dell" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the documents from a collection using find() method −

> db.updateNestedValueDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
   "CustomerName" : "Chris",
   "CustomerDetails" : {
      "CustomerAge" : 25,
      "CustomerCompanyName" : "Dell",
      "CustomerCityName" : "US"
   }
}

Look at the above sample output, the nested field “CustomerCompanyName” has been changed from “Google” to “Dell”.

raja
Published on 29-Mar-2019 13:53:13
Advertisements