MongoDB Query to combine AND & OR?


To combine AND & OR in MongoDB, let us first create a collection with documents −

>db.combinedAndOrDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentSkill":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd306dcb64f4b851c3a13e2")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Larry","StudentAge":21,"StudentSkill":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd306f3b64f4b851c3a13e3")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Sam","StudentAge":24,"StudentSkill":"SQL Server"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd30701b64f4b851c3a13e4")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"),
   "StudentFirstName" : "John",
   "StudentAge" : 23,
   "StudentSkill" : "MongoDB"
}
{
   "_id" : ObjectId("5cd306f3b64f4b851c3a13e3"),
   "StudentFirstName" : "Larry",
   "StudentAge" : 21,
   "StudentSkill" : "MySQL"
}
{
   "_id" : ObjectId("5cd30701b64f4b851c3a13e4"),
   "StudentFirstName" : "Sam",
   "StudentAge" : 24,
   "StudentSkill" : "SQL Server"
}

Following is the query for combined AND & OR −

> db.combinedAndOrDemo.find( {"$or":[ {"$and": [{"StudentFirstName": "John"}, {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}] }, {"StudentSkill" : "MongoDB" } ] } );

This will produce the following output −

{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements