Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
