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

Deleting specific record from an array nested within another array in MongoDB



To delete specific record, use “$pull” and since we are updating the already created collection, use UPDATE().

Let us create a collection with documents −

> db.demo213.insertOne({
...   "id": 101,
...   "details1": [
...      {
...         "Name": "Chris",
...         "details2": [
...            {
...               "StudentName": "David",
...               "Subject": "MongoDB"
...            },
...            {
...               "StudentName": "Mike",
...               "Subject": "MySQL"
...            }
...         ]
...
...      }
...   ]
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e300c03d395bdc2134704")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e3e300c03d395bdc2134704"),
   "id" : 101,
   "details1" : [
      {
         "Name" : "Chris",
         "details2" : [
            {
               "StudentName" : "David",
               "Subject" : "MongoDB"
            },
            {
               "StudentName" : "Mike",
               "Subject" : "MySQL"
            }
         ]
      }
   ]
}

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

> db.demo213.update({"id": 101, "details1.Name": "Chris"},
...   {
...      "$pull": {"details1.$.details2" : { "Subject": "MySQL" }}
...   }, multi=true
...)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e3e300c03d395bdc2134704"),
   "id" : 101,
   "details1" : [
      {
         "Name" : "Chris",
         "details2" : [
            {
               "StudentName" : "David",
               "Subject" : "MongoDB"
            }
         ]
      }
   ]
}
Updated on: 2020-03-27T11:14:03+05:30

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements