How to add a sub-document to sub-document array in MongoDB?


Use the $push operator to add a sub-document. Let us first create a collection with documents −

> db.subDocumentToSubDocumentDemo.insertOne(
   {
      "_id" :101,
      "StudentName" : "Larry",
      "StudentAge" : 21,
      "StudentDetails" : [
         {
            "StudentCountryName" : "US",
            "StudentFavouriteSubjectList" : [ ]
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentFavouriteSubjectList" : [ ]
      }
   ]
}

Following is the query to add a sub-document to sub-document array in MongoDB −

> db.subDocumentToSubDocumentDemo.update(
   { "_id": 101 },
   {
      "$push": {
         "StudentDetails": {
            "StudentCountryName" : "UK",
            "StudentFavouriteSubjectList" : ["MongoDB","Java" ]
         }
      }
   }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check all the documents once again −

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

This will produce the following output −

{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentFavouriteSubjectList" : [ ]
      },
      {
         "StudentCountryName" : "UK",
         "StudentFavouriteSubjectList" : [
            "MongoDB",
            "Java"
         ]
      }
   ]
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements