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
MongoDB query to remove entire array from collection?
To remove an entire array field from all documents in a MongoDB collection, use the $unset operator. This completely removes the specified field from the documents.
Syntax
db.collection.updateMany(
{},
{ $unset: { "arrayFieldName": "" } }
);
Sample Data
Let us create a collection with documents containing array fields ?
db.demo609.insertMany([
{ "ListOfSubject": ["MySQL", "MongoDB"] },
{ "ListOfSubject": ["Java"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e974695f57d0dc0b182d62c"),
ObjectId("5e97469af57d0dc0b182d62d")
]
}
Display all documents from the collection ?
db.demo609.find();
{ "_id": ObjectId("5e974695f57d0dc0b182d62c"), "ListOfSubject": ["MySQL", "MongoDB"] }
{ "_id": ObjectId("5e97469af57d0dc0b182d62d"), "ListOfSubject": ["Java"] }
Example: Remove Entire Array Field
Here is the query to remove the entire array field from all documents ?
db.demo609.updateMany(
{},
{ $unset: { "ListOfSubject": "" } }
);
{
"acknowledged": true,
"matchedCount": 2,
"modifiedCount": 2
}
Verify Result
Display all documents to confirm the array field has been removed ?
db.demo609.find();
{ "_id": ObjectId("5e974695f57d0dc0b182d62c") }
{ "_id": ObjectId("5e97469af57d0dc0b182d62d") }
Key Points
-
$unsetcompletely removes the specified field from documents. - Use
updateMany()with an empty filter{}to target all documents. - The value in
$unsetcan be an empty string""or any value − MongoDB ignores it.
Conclusion
The $unset operator with updateMany() effectively removes entire array fields from all documents in a collection. This operation permanently deletes the field, not just its contents.
Advertisements
