Delete all elements in an array field in MongoDB?

To delete all elements in an array field in MongoDB, use the $set operator to replace the array field with an empty array []. This effectively clears all elements while preserving the field structure.

Syntax

db.collection.updateMany(
    {},
    { $set: { "arrayFieldName": [] } }
);

Sample Data

db.deleteAllElementsInArrayDemo.insertMany([
    {
        "InstructorName": "Larry",
        "InstructorTechnicalSubject": ["Java", "MongoDB"]
    },
    {
        "InstructorName": "Mike", 
        "InstructorTechnicalSubject": ["C", "C++", "Python"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c8fb971d3c9d04998abf00e"),
        ObjectId("5c8fb98ad3c9d04998abf00f")
    ]
}

Before Deletion

db.deleteAllElementsInArrayDemo.find().pretty();
{
    "_id": ObjectId("5c8fb971d3c9d04998abf00e"),
    "InstructorName": "Larry",
    "InstructorTechnicalSubject": [
        "Java",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5c8fb98ad3c9d04998abf00f"),
    "InstructorName": "Mike",
    "InstructorTechnicalSubject": [
        "C",
        "C++",
        "Python"
    ]
}

Delete All Array Elements

db.deleteAllElementsInArrayDemo.updateMany(
    {},
    { $set: { "InstructorTechnicalSubject": [] } }
);
{
    "acknowledged": true,
    "matchedCount": 2,
    "modifiedCount": 2
}

After Deletion

db.deleteAllElementsInArrayDemo.find().pretty();
{
    "_id": ObjectId("5c8fb971d3c9d04998abf00e"),
    "InstructorName": "Larry",
    "InstructorTechnicalSubject": []
}
{
    "_id": ObjectId("5c8fb98ad3c9d04998abf00f"),
    "InstructorName": "Mike",
    "InstructorTechnicalSubject": []
}

Conclusion

Use $set with an empty array [] to clear all elements from array fields. The updateMany() method with an empty filter {} applies the operation to all documents in the collection.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements