MongoDB query to remove entire array from collection?

MongoDBDatabaseBig Data Analytics

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") }
raja
Published on 15-May-2020 11:34:08
Advertisements