Removing an object in a child collection in MongoDB?

To remove an object in a child collection in MongoDB, use the $pull operator combined with the $ positional operator to target the specific nested array and remove matching elements.

Syntax

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

Sample Data

db.demo715.insertOne({
    _id: 1,
    details: [
        {
            'id': '101',
            'Information': [
                {
                    'studentid': '102',
                    "Name": "Bob"
                },
                {
                    'studentid': '103',
                    "Name": "Chris"
                }
            ]
        }
    ]
});
{ "acknowledged": true, "insertedId": 1 }

Display all documents from the collection ?

db.demo715.find();
{ "_id": 1, "details": [ { "id": "101", "Information": [ { "studentid": "102", "Name": "Bob" }, { "studentid": "103", "Name": "Chris" } ] } ] }

Example: Remove Object from Child Collection

Remove the student with studentid "102" from the Information array ?

db.demo715.update(
    {"details.id": '101'},
    { $pull: { 'details.$.Information': {studentid: '102', "Name": "Bob"} } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo715.find();
{ "_id": 1, "details": [ { "id": "101", "Information": [ { "studentid": "103", "Name": "Chris" } ] } ] }

Key Points

  • The $ operator matches the first element in the parent array that satisfies the query condition.
  • $pull removes all elements from the nested array that match the specified criteria.
  • You must specify the complete object to match when using $pull on object arrays.

Conclusion

Use $pull with the positional operator $ to remove specific objects from nested arrays. The query first identifies the parent array element, then removes matching child objects based on your criteria.

Updated on: 2026-03-15T03:41:48+05:30

671 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements