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

To delete a specific record from an array nested within another array in MongoDB, use the $pull operator combined with the $ positional operator to target elements in nested arrays.

Syntax

db.collection.update(
    {"parentArray.field": "value"},
    { $pull: { "parentArray.$.nestedArray": { "field": "matchValue" } } }
);

Sample Data

Let us first create a collection with nested array documents ?

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

Display all documents from the collection ?

db.deletingSpecificRecordDemo.find().pretty();
{
    "_id": ObjectId("5cf2210ab64a577be5a2bc06"),
    "StudentDetails": [
        {
            "StudentName": "John",
            "StudentSubjectDetails": [
                {
                    "Subject": "MongoDB",
                    "Marks": 45
                },
                {
                    "Subject": "MySQL",
                    "Marks": 67
                }
            ]
        }
    ]
}

Delete Specific Record from Nested Array

Remove the MongoDB subject record (Marks: 45) from John's StudentSubjectDetails ?

db.deletingSpecificRecordDemo.update(
    {"_id": ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetails.StudentName": "John"},
    {
        "$pull": {"StudentDetails.$.StudentSubjectDetails": {"Marks": 45}}
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check the document after deletion ?

db.deletingSpecificRecordDemo.find().pretty();
{
    "_id": ObjectId("5cf2210ab64a577be5a2bc06"),
    "StudentDetails": [
        {
            "StudentName": "John",
            "StudentSubjectDetails": [
                {
                    "Subject": "MySQL",
                    "Marks": 67
                }
            ]
        }
    ]
}

How It Works

  • $pull removes matching array elements
  • $ identifies the matched parent array element
  • The combination targets specific nested array elements for removal

Conclusion

Use $pull with the positional $ operator to delete specific records from nested arrays. The $ targets the parent array element, while $pull removes matching nested elements based on specified criteria.

Updated on: 2026-03-15T01:28:28+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements