How to remove object from array in MongoDB?

You can use $pull operator to remove objects from an array in MongoDB. The $pull operator removes all array elements that match a specified query condition.

Syntax

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

Sample Data

Let us create a collection with a document containing an array of objects ?

db.removeObjectFromArrayDemo.insertOne({
    "StudentName": "John",
    "StudentAcademicProjectDetails": [
        {
            "StudentProjectId": 101,
            "StudentProjectName": "Pig Dice Game"
        },
        {
            "StudentProjectId": 110,
            "StudentProjectName": "Library Management System"
        },
        {
            "StudentProjectId": 120,
            "StudentProjectName": "Phonebook Management System"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c8ad13d6cea1f28b7aa0817")
}

Display the document using find() method ?

db.removeObjectFromArrayDemo.find().pretty();
{
    "_id": ObjectId("5c8ad13d6cea1f28b7aa0817"),
    "StudentName": "John",
    "StudentAcademicProjectDetails": [
        {
            "StudentProjectId": 101,
            "StudentProjectName": "Pig Dice Game"
        },
        {
            "StudentProjectId": 110,
            "StudentProjectName": "Library Management System"
        },
        {
            "StudentProjectId": 120,
            "StudentProjectName": "Phonebook Management System"
        }
    ]
}

Example: Remove Object by Field Value

Remove the project with StudentProjectId: 101 from the array ?

db.removeObjectFromArrayDemo.update(
    { "_id": ObjectId("5c8ad13d6cea1f28b7aa0817") },
    { $pull: { "StudentAcademicProjectDetails": { "StudentProjectId": 101 } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check if the object has been removed from the array ?

db.removeObjectFromArrayDemo.find().pretty();
{
    "_id": ObjectId("5c8ad13d6cea1f28b7aa0817"),
    "StudentName": "John",
    "StudentAcademicProjectDetails": [
        {
            "StudentProjectId": 110,
            "StudentProjectName": "Library Management System"
        },
        {
            "StudentProjectId": 120,
            "StudentProjectName": "Phonebook Management System"
        }
    ]
}

Key Points

  • $pull removes all matching elements from the array
  • Use specific field conditions to target exact objects
  • The operation modifies the original document in place

Conclusion

The $pull operator efficiently removes objects from MongoDB arrays by matching specific field criteria. It removes all array elements that satisfy the given condition, making it ideal for cleaning up array data.

Updated on: 2026-03-15T00:10:46+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements