Add a field to an embedded document in an array in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use update() along with $ operator for this. Let us first create a collection with documents −

> db.addAFieldDemo.insertOne(
...   {
...
...      "ClientName" : "Larry",
...      "ClientCountryName" : "US",
...      "ClientOtherDetails" : [
...         {
...            "ClientProjectName":"Online Banking System"
...         }
...      ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd44bdc2cba06f46efe9ee8")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
   "ClientName" : "Larry",
   "ClientCountryName" : "US",
   "ClientOtherDetails" : [
      {
         "ClientProjectName" : "Online Banking System"
      }
   ]
}

Following is the query to add a field to an embedded document in an array −

> db.addAFieldDemo.update({ClientOtherDetails:{$elemMatch:{"ClientProjectName" : "Online Banking System"}}},
... {$set :{'ClientOtherDetails.$.isMarried':true}},true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display all the documents from the above collection −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
   "ClientName" : "Larry",
   "ClientCountryName" : "US",
   "ClientOtherDetails" : [
      {
         "ClientProjectName" : "Online Banking System",
         "isMarried" : true
      }
   ]
}
raja
Published on 23-May-2019 09:03:51
Advertisements