MongoDB pull with positional operator?

The $pull operator combined with the positional operator ($) in MongoDB allows you to remove specific values from arrays within nested documents. Use $elemMatch to identify the target document and $ to reference the matched array element.

Syntax

db.collection.update(
    { 
        "arrayField": { 
            "$elemMatch": { 
                "field": "matchValue" 
            } 
        } 
    },
    { 
        "$pull": { 
            "arrayField.$.nestedArray": "valueToRemove" 
        } 
    }
);

Sample Data

db.pullWithPositionalOperatorDemo.insertOne({
    _id: 100,
    "StudentDetails": [
        {
            "StudentId": "STU-1",
            "StudentFavouriteSubject": ["MongoDB", "Java"]
        },
        {
            "StudentId": "STU-2",
            "StudentFavouriteSubject": ["PHP", "MySQL"]
        }
    ]
});
{ "acknowledged": true, "insertedId": 100 }

Example: Remove Subject from Specific Student

Let's remove "MySQL" from STU-2's favourite subjects ?

db.pullWithPositionalOperatorDemo.update(
    {
        "StudentDetails": {
            "$elemMatch": {
                "StudentId": "STU-2",
                "StudentFavouriteSubject": "MySQL"
            }
        }
    },
    {
        "$pull": {
            "StudentDetails.$.StudentFavouriteSubject": "MySQL"
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.pullWithPositionalOperatorDemo.find().pretty();
{
    "_id": 100,
    "StudentDetails": [
        {
            "StudentId": "STU-1",
            "StudentFavouriteSubject": [
                "MongoDB",
                "Java"
            ]
        },
        {
            "StudentId": "STU-2",
            "StudentFavouriteSubject": [
                "PHP"
            ]
        }
    ]
}

Key Points

  • $elemMatch identifies the specific array element that matches multiple conditions
  • $ references the first matched element from the query condition
  • $pull removes all instances of the specified value from the target array

Conclusion

Combining $pull with the positional operator enables precise removal of values from nested arrays. Use $elemMatch to match the target document and $ to reference the matched element position.

Updated on: 2026-03-15T01:09:43+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements