- 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
Delete data from a collection in MongoDB using multiple conditions?
You can use remove() for this. Let us first create a collection with documents −
> db.deleteDataDemo.insertOne({_id:1,"Name":"Larry"}); { "acknowledged" : true, "insertedId" : 1 } > db.deleteDataDemo.insertOne({_id:2,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : 2 } > db.deleteDataDemo.insertOne({_id:3,"Name":"Robert"}); { "acknowledged" : true, "insertedId" : 3 } > db.deleteDataDemo.insertOne({_id:4,"Name":"David"}); { "acknowledged" : true, "insertedId" : 4 } > db.deleteDataDemo.insertOne({_id:5,"Name":"Carol"}); { "acknowledged" : true, "insertedId" : 5 } > db.deleteDataDemo.insertOne({_id:6,"Name":"Sam"}); { "acknowledged" : true, "insertedId" : 6 }
Following is the query to display all documents from a collection with the help of find() method −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" } { "_id" : 2, "Name" : "Chris" } { "_id" : 3, "Name" : "Robert" } { "_id" : 4, "Name" : "David" } { "_id" : 5, "Name" : "Carol" } { "_id" : 6, "Name" : "Sam" }
Following is the query to delete data from a collection in MongoDB by using multiple conditions. Here we have used two conditions i.e. _id 4 and Name David −
> db.deleteDataDemo.remove({'_id':4,'Name':"David"}); WriteResult({ "nRemoved" : 1 })
Let us check all the documents once again −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" } { "_id" : 2, "Name" : "Chris" } { "_id" : 3, "Name" : "Robert" } { "_id" : 5, "Name" : "Carol" } { "_id" : 6, "Name" : "Sam" }
Advertisements