MongoDB $push in nested array?


Here, $push can be used to add new documents in nested array. To understand the above $push concept, let us create a collection with nested array document. The query to create a collection with document is as follows:

>db.nestedArrayDemo.insertOne({"EmployeeName":"Larry","EmployeeSalary":9000,"EmployeeDetails":
   [{"EmployeeDOB":new Date('1990-01-21'),"EmployeeDepartment":"ComputerScience","EmployeeProject":
   [{"Technology":"C","Duration":6},{"Technology":"Java","Duration":7}]}]});

The following is the output:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d73090c3d5054b766a76e")
}

Now you can display documents from a collection with the help of find() method. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            }
         ]
      }
   ]
}

Here is the demo of $push in nested array to add new documents. The query is as follows:

>db.nestedArrayDemo.update({"_id":ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeDetails.EmployeeDepartment":"ComputerScience"}, {"$push":
   {"EmployeeDetails.$.EmployeeProject": {"Technology":"Python", "Duration":4 }}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

In the above query, I have added a document {"Technology":"Python", "Duration":4 } in nested array. Now display the documents from the collection once again. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            },
            {
               "Technology" : "Python",
               "Duration" : 4
            }
         ]
      }
   ]
}

Updated on: 26-Jun-2020

827 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements