Syntax error Delete specific record from an array nested within another array in MongoDB?

Delete specific record from an array nested within another array in MongoDB?



To delete specific record, use $pull operator. Let us first create a collection with documents −

> dbdeletingSpecificRecordDemoinsertOne(
   {
      "StudentDetails": [
         {
            "StudentName": "John",
            "StudentSubjectDetails": [
               {
                  "Subject": "MongoDB",
                  "Marks":45
               },
               {
                  "Subject": "MySQL",
                  "Marks":67
               }
            ]
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf2210ab64a577be5a2bc06")
}

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

> dbdeletingSpecificRecordDemofind()pretty();

This will produce the following document −

{
   "_id" : ObjectId("5cf2210ab64a577be5a2bc06"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentSubjectDetails" : [
            {
               "Subject" : "MongoDB",
               "Marks" : 45
            },
            {
               "Subject" : "MySQL",
               "Marks" : 67
            }
         ]
      }
   ]
}

Here is the query to delete specific record from an array nested within another array −

> dbdeletingSpecificRecordDemoupdate({"_id": ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetailsStudentName" : "John"},
   {
      "$pull": {"StudentDetails$StudentSubjectDetails" : { "Marks":45 }}
   }, multi=true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

> dbdeletingSpecificRecordDemofind()pretty();

This will produce the following document −

{
   "_id" : ObjectId("5cf2210ab64a577be5a2bc06"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentSubjectDetails" : [
            {
               "Subject" : "MySQL",
               "Marks" : 67
            }
         ]
      }
   ]
}
Updated on: 2019-07-30T22:30:26+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements