- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to delete multiple documents in MongoDB using deleteMany()?
Let us first create a collection with documents −
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b07bf3115999ed51214") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0bbf3115999ed51215") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0fbf3115999ed51216") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b12bf3115999ed51217") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b18bf3115999ed51218") }
Following is the query to display all documents from a collection with the help of find() method −
> db.deleteMultipleDocumentsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce00b07bf3115999ed51214"), "StudentFirstName" : "Larry" } { "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b0fbf3115999ed51216"), "StudentFirstName" : "David" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" } { "_id" : ObjectId("5ce00b18bf3115999ed51218"), "StudentFirstName" : "Carol" }
Following is the query to delete multiple documents in MongoDB −
> db.deleteMultipleDocumentsDemo.deleteMany({StudentFirstName: {$in: ["Larry", "David", "Carol"]}}); { "acknowledged" : true, "deletedCount" : 3 }
Let us display the document once again −
> db.deleteMultipleDocumentsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" }
Advertisements