How to add an extra field in a sub document in MongoDB?


You can use update(). Let us first create a collection with documents −

> db.addExtraFieldDemo.insertOne(
   {
      "_id": 1,
      "UserName": "Larry" ,
      "UserOtherDetails":[
         {
            "UserCountryName": "US",
            "UserAge":23
         },
         {
            "UserCountryName": "UK",
            "UserAge":24
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 1 }

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

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

This will produce the following output −

{
   "_id" : 1,
   "UserName" : "Larry",
   "UserOtherDetails" : [
      {
         "UserCountryName" : "US",
         "UserAge" : 23
      },
      {
         "UserCountryName" : "UK",
         "UserAge" : 24
      }
   ]
}

Following is the query to add an extra field in a sub document in MongoDB −

> db.addExtraFieldDemo.update({ "_id":1},{ "$set":{ "UserOtherDetails.0.isMarried_" : true }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the documents once again −

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

This will produce the following output −

{
   "_id" : 1,
   "UserName" : "Larry",
   "UserOtherDetails" : [
      {
         "UserCountryName" : "US",
         "UserAge" : 23,
         "isMarried_" : true
      },
      {
         "UserCountryName" : "UK",
         "UserAge" : 24
      }
   ]
}

Updated on: 30-Jul-2019

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements