Remove Entire Array from Collection in MongoDB



To remove the entire array from the collection, use $unset in MongoDB. Let us create a collection with documents −

> db.demo609.insertOne({"ListOfSubject":["MySQL","MongoDB"]});{
   "acknowledged" : true, "insertedId" : ObjectId("5e974695f57d0dc0b182d62c")
}
> db.demo609.insertOne({"ListOfSubject":["Java"]});{
   "acknowledged" : true, "insertedId" : ObjectId("5e97469af57d0dc0b182d62d")
}

Display all documents from a collection with the help of find() method −

> db.demo609.find();

This will produce the following output −

{ "_id" : ObjectId("5e974695f57d0dc0b182d62c"), "ListOfSubject" : [ "MySQL", "MongoDB" ] }
{ "_id" : ObjectId("5e97469af57d0dc0b182d62d"), "ListOfSubject" : [ "Java" ] }

Here is the query to remove the entire array from collection −

> db.demo609.update({},{$unset:{"ListOfSubject":""}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Display all documents from a collection with the help of find() method −

> db.demo609.find();

This will produce the following output −

{ "_id" : ObjectId("5e974695f57d0dc0b182d62c") }
{ "_id" : ObjectId("5e97469af57d0dc0b182d62d") }
Updated on: 2020-05-15T08:04:29+05:30

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements