Pull an element in sub of sub-array in MongoDB?

To pull an element from a sub-array within a nested array in MongoDB, use $pull combined with the $ positional operator. This allows you to target and remove specific elements from deeply nested array structures.

Syntax

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

Create Sample Data

db.demo679.insertOne({
    id: 1,
    "details": [
        {
            CountryName: "US",
            "information": [
                { "Name": "Chris", "FirstName": "Name=Chris" },
                { "Name": "Bob", "FirstName": "Name=Bob" }
            ]
        },
        {
            CountryName: "UK",
            "information": [
                { "Name": "Robert", "FirstName": "Name=Robert" },
                { "Name": "Sam", "FirstName": "Name=Sam" }
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea442cf04263e90dac943fd")
}

Example: Remove Element from Nested Array

Remove Bob's record from the US country's information array ?

db.demo679.update(
    { "details.CountryName": "US" },
    { $pull: { "details.$.information": { "Name": "Bob", "FirstName": "Name=Bob" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo679.find().pretty();
{
    "_id": ObjectId("5ea442cf04263e90dac943fd"),
    "id": 1,
    "details": [
        {
            "CountryName": "US",
            "information": [
                {
                    "Name": "Chris",
                    "FirstName": "Name=Chris"
                }
            ]
        },
        {
            "CountryName": "UK",
            "information": [
                {
                    "Name": "Robert",
                    "FirstName": "Name=Robert"
                },
                {
                    "Name": "Sam",
                    "FirstName": "Name=Sam"
                }
            ]
        }
    ]
}

How It Works

  • The query {"details.CountryName": "US"} matches the parent array element
  • $ identifies the matched array element (US country record)
  • $pull removes the specified object from the information sub-array

Conclusion

Use $pull with the $ positional operator to remove elements from nested arrays. The $ targets the matched parent element, while $pull removes the specified sub-array element that matches all provided field-value pairs.

Updated on: 2026-03-15T03:28:50+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements