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

MongoDBDatabaseBig Data Analytics

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"
            }
         ]
      }
   ]
}
raja
Published on 27-Mar-2020 15:43:39
Advertisements