Insert data into inner array in MongoDB?


You can use $addToSet operator for this. Let us first create a collection with documents −

> db.insertDataIntoArrayDemo.insertOne(
   {
      "UserDetails":[
         {
            "UserId" :"user121",
            "userGroupMessage":[]
         },
         {
            "UserId" :"user221",
            "userGroupMessage":["Cool","Good Morning"]
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd694e157806ebf1256f128")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd694e157806ebf1256f128"),
   "UserDetails" : [
      {
         "UserId" : "user121",
         "userGroupMessage" : [ ]
      },
      {
         "UserId" : "user221",
         "userGroupMessage" : [
            "Cool",
            "Good Morning"
         ]
      }
   ]
}

Following is the query to insert data into inner array in MongoDB −

> db.insertDataIntoArrayDemo.update({"UserDetails.UserId":"user121"},
   {"$addToSet":{"UserDetails.$.userGroupMessage":"Hello"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd694e157806ebf1256f128"),
   "UserDetails" : [
      {
         "UserId" : "user121",
         "userGroupMessage" : [
            "Hello"
         ]
      },
      {
         "UserId" : "user221",
         "userGroupMessage" : [
            "Cool",
            "Good Morning"
         ]
      }
   ]
}

Updated on: 30-Jul-2019

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements