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

  • $unset completely removes the specified field from documents.
  • Use updateMany() with an empty filter {} to target all documents.
  • The value in $unset can 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.

Updated on: 2026-03-15T03:49:42+05:30

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements