How to pull all elements from an array in MongoDB without any condition?

To pull all elements from an array in MongoDB without any condition, use the $set operator to replace the entire array field with an empty array []. This effectively removes all elements from the specified array.

Syntax

db.collection.update(
    { "field": "value" },
    { $set: { "arrayField": [] } }
);

Sample Data

Let us create a collection with documents containing arrays ?

db.pullAllElementDemo.insertMany([
    {
        "StudentId": 101,
        "StudentDetails": [
            {
                "StudentName": "Carol",
                "StudentAge": 21,
                "StudentCountryName": "US"
            },
            {
                "StudentName": "Chris",
                "StudentAge": 24,
                "StudentCountryName": "AUS"
            }
        ]
    },
    {
        "StudentId": 102,
        "StudentDetails": [
            {
                "StudentName": "Robert",
                "StudentAge": 27,
                "StudentCountryName": "UK"
            },
            {
                "StudentName": "David",
                "StudentAge": 23,
                "StudentCountryName": "US"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ccdd9c8685b30d09a7111e4"),
        ObjectId("5ccdd9f7685b30d09a7111e5")
    ]
}

Example: Pull All Elements from Array

Remove all StudentDetails elements from document with StudentId 102 using $set ?

db.pullAllElementDemo.update(
    { StudentId: 102 },
    { $set: { "StudentDetails": [] } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all documents to verify the array has been emptied ?

db.pullAllElementDemo.find().pretty();
{
    "_id": ObjectId("5ccdd9c8685b30d09a7111e4"),
    "StudentId": 101,
    "StudentDetails": [
        {
            "StudentName": "Carol",
            "StudentAge": 21,
            "StudentCountryName": "US"
        },
        {
            "StudentName": "Chris",
            "StudentAge": 24,
            "StudentCountryName": "AUS"
        }
    ]
}
{
    "_id": ObjectId("5ccdd9f7685b30d09a7111e5"),
    "StudentId": 102,
    "StudentDetails": []
}

Conclusion

Use $set with an empty array [] to pull all elements from an array field in MongoDB. This approach completely empties the array while preserving the field structure in the document.

Updated on: 2026-03-15T00:57:30+05:30

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements