Implement multiple conditions in MongoDB?


Let us first create a collection with documents −

> db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }

Following is the query to display all documents from a collection with the help of find() method −

> db.multipleConditionDemo.find().pretty();

This will produce the following output −

{ "_id" : 1, "Name" : "John" }
{ "_id" : 2, "Name" : "Carol" }
{ "_id" : 3, "Name" : "Sam" }
{ "_id" : 4, "Name" : "David" }

Following is the query to implement multiple conditions in WHERE clause −

> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });
WriteResult({ "nRemoved" : 2 })

Let us check the documents from the above collection once again −

> db.multipleConditionDemo.find().pretty();

This will produce the following output −

{ "_id" : 1, "Name" : "John" }
{ "_id" : 4, "Name" : "David" }

Updated on: 30-Jul-2019

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements