Clearing items in a nested MongoDB array?

To clear items in a nested MongoDB array, use the $set operator to replace the entire array field with an empty array []. This removes all elements from the specified array field.

Syntax

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

Sample Data

Let us create a collection with nested arrays ?

db.clearingItemsInNestedArrayDemo.insertOne({
    "StudentName": "John",
    "StudentDetails": [
        {
            "ProjectName": "Online Banking",
            "ProjectDetails": [
                {
                    "TechnologyUsed": "Java",
                    "TeamSize": 5
                }
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c9930b4330fd0aa0d2fe4ce")
}

Display Current Data

db.clearingItemsInNestedArrayDemo.find().pretty();
{
    "_id": ObjectId("5c9930b4330fd0aa0d2fe4ce"),
    "StudentName": "John",
    "StudentDetails": [
        {
            "ProjectName": "Online Banking",
            "ProjectDetails": [
                {
                    "TechnologyUsed": "Java",
                    "TeamSize": 5
                }
            ]
        }
    ]
}

Clear the Nested Array

db.clearingItemsInNestedArrayDemo.update(
    { "StudentName": "John" },
    { $set: { "StudentDetails": [] } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.clearingItemsInNestedArrayDemo.find().pretty();
{
    "_id": ObjectId("5c9930b4330fd0aa0d2fe4ce"),
    "StudentName": "John",
    "StudentDetails": []
}

Conclusion

Use $set with an empty array [] to clear all items from a nested array field. This approach completely replaces the array content while preserving the field structure.

Updated on: 2026-03-15T00:26:48+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements