
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 Multiple IDs in MongoDB
To delete multiple ids in MongoDB, you can use $in operator. Following is the syntax
db.yourCollectionName.remove( { _id : { $in: [yourObjectId1, yourObjectId2, yourObjectId3)] } } );
Let us create a collection with documents
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Chris","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7d6a629b87623db1b19") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Robert","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7dea629b87623db1b1a") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Sam","ClientAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7e9a629b87623db1b1b") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"John","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7f7a629b87623db1b1c") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Carol","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd803a629b87623db1b1d") }
Following is the query to display all documents from a collection with the help of find() method
> db.deleteMultipleIdsDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9cd7d6a629b87623db1b19"), "ClientName" : "Chris", "ClientAge" : 26 } { "_id" : ObjectId("5c9cd7dea629b87623db1b1a"), "ClientName" : "Robert", "ClientAge" : 28 } { "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5c9cd803a629b87623db1b1d"), "ClientName" : "Carol", "ClientAge" : 36 }
Following is the query to delete multiple ids in MongoDB
> db.deleteMultipleIdsDemo.remove( { _id : { $in: [ObjectId("5c9cd7dea629b87623db1b1a"), ... ObjectId("5c9cd803a629b87623db1b1d"), ... ObjectId("5c9cd7d6a629b87623db1b19") ... ] } } ); WriteResult({ "nRemoved" : 3 })
Let us check the multiple ids have been deleted or not
> db.deleteMultipleIdsDemo.find().pretty();
The following is the output displaying we have successfully deleted 3 ids and now only 2 are remaining
{ "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 }
Advertisements