MongoDB query to get documents with multiple conditions set in $or?


Let us create a collection with documents −

> db.demo711.insertOne({Name:"John","Marks":75,Age:21,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c215d33e20ed1097b7e")
}
> db.demo711.insertOne({Name:"Chris","Marks":55,Age:22,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c2c5d33e20ed1097b7f")
}
> db.demo711.insertOne({Name:"Bob","Marks":45,Age:20,status:"Inactive"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c3e5d33e20ed1097b80")
}
> db.demo711.insertOne({Name:"David","Marks":85,Age:23,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c775d33e20ed1097b81")
}

Display all documents from a collection with the help of find() method −

> db.demo711.find();

This will produce the following output −

{ "_id" : ObjectId("5ea85c215d33e20ed1097b7e"), "Name" : "John", "Marks" : 75, "Age" : 21, "status" : "Active" }
{ "_id" : ObjectId("5ea85c2c5d33e20ed1097b7f"), "Name" : "Chris", "Marks" : 55, "Age" : 22, "status" : "Active" }
{ "_id" : ObjectId("5ea85c3e5d33e20ed1097b80"), "Name" : "Bob", "Marks" : 45, "Age" : 20, "status" : "Inactive" }
{ "_id" : ObjectId("5ea85c775d33e20ed1097b81"), "Name" : "David", "Marks" : 85, "Age" : 23, "status" : "Active" }

Following is the MongoDB query with $or −

> db.demo711.find( { $or: [ { Age: {$gte:23}}, {Marks:{$gt:80} }, {status: 'Inactive'} ] }) ;

This will produce the following output −

{ "_id" : ObjectId("5ea85c3e5d33e20ed1097b80"), "Name" : "Bob", "Marks" : 45, "Age" : 20, "status" : "Inactive" }
{ "_id" : ObjectId("5ea85c775d33e20ed1097b81"), "Name" : "David", "Marks" : 85, "Age" : 23, "status" : "Active" }

Updated on: 14-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements