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" }

Updated on: 30-Jul-2019

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements