
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete All Elements in an Array Field in MongoDB
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" : [ ] }
Advertisements