Delete all elements in an array field in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $set operator for this. The syntax is as follows −

db.yourCollectionName.update({}, { $set : {"yourFieldName": [] }} , {multi:true} );

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fb971d3c9d04998abf00e")
}
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Mike","InstructorTechnicalSubject":["C","C++","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fb98ad3c9d04998abf00f")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.deleteAllElementsInArrayDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [
      "Java",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
   "InstructorName" : "Mike",
   "InstructorTechnicalSubject" : [
      "C",
      "C++",
      "Python"
   ]
}

Here is the query to delete all elements in the array field −

> db.deleteAllElementsInArrayDemo.update({}, { $set : {"InstructorTechnicalSubject": [] }} , {multi:true} );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Let us now check all the documents from a collection using find(). The query is as follows −

> db.deleteAllElementsInArrayDemo.find().pretty();

The following is the output. We have deleted all the elements of the “InstructorTechnicalSubject” array field:

{
   "_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [ ]
}
{
   "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
   "InstructorName" : "Mike",
   "InstructorTechnicalSubject" : [ ]
}
raja
Published on 29-Mar-2019 13:40:31
Advertisements