How to add new item in nested array with MongoDB?


For this, use find() along with update(). Let us create a collection with documents −

> db.demo124.insertOne(
...    {
...       "Name" : "John",
...       "Id" : 101,
...       "ProjectDetails" : [{
...          "ProjectName1" : "Online Book",
...          "ProjectName2" : "Online Banking"
...    }, {
...          "ProjectName1" : "Online Library Management System",
...          "ProjectName2" : "School Management System"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f2c8b140daf4c2a3544bb")
}

Display all documents from a collection with the help of find() method −

> db.demo124.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"), "Name" : "John", "Id" : 101, "ProjectDetails" : [
      { "ProjectName1" : "Online Book", "ProjectName2" : "Online Banking" },
      { "ProjectName1" : "Online Library Management System", "ProjectName2" : "School Management System" }
   ] 
}

Following is the query to add new item in nested array −

> db.demo124.find().toArray().forEach(
...    function(d){
...       for(var i = 0; i< d.ProjectDetails.length; ++i) {
...          d.ProjectDetails[i]['ProjectName3'] = 'Online Snake Game';
...       }
...       db.demo124.update({_id: d._id}, d);
...    }
... );

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"),
   "Name" : "John",
   "Id" : 101,
   "ProjectDetails" : [
      {
         "ProjectName1" : "Online Book",
         "ProjectName2" : "Online Banking",
         "ProjectName3" : "Online Snake Game"
      },
      {
         "ProjectName1" : "Online Library Management System",
         "ProjectName2" : "School Management System",
         "ProjectName3" : "Online Snake Game"
      }
   ]
}

Updated on: 31-Mar-2020

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements