MongoDB query to remove element from array as sub property

To remove an element from an array that exists as a sub-property in MongoDB, use the $pull operator with dot notation to target the nested array field.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.demo388.insertOne({
    _id: '101',
    userDetails: {
        isMarried: false,
        userInfo: [
            {
                Name: "Chris",
                Age: 21
            }
        ]
    }
});
{ "acknowledged" : true, "insertedId" : "101" }

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

db.demo388.find();
{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ { "Name" : "Chris", "Age" : 21 } ] } }

Example: Remove Element from Nested Array

Following is the query to remove element from array as sub property ?

db.demo388.update(
    { "_id": "101" },
    { "$pull": { "userDetails.userInfo": { "Name": "Chris" } } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify Result

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

db.demo388.find();
{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ ] } }

Conclusion

Use $pull with dot notation to remove elements from nested arrays. The operator matches and removes all array elements that satisfy the specified condition, leaving an empty array if all elements are removed.

Updated on: 2026-03-15T02:46:31+05:30

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements