MongoDB: combining AND and OR?


Let us first create a collection with documents −

> db.demo293.insertOne({FirstName:"Chris",LastName:"Brown",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45075d93261e4bc9ea32")
}
> db.demo293.insertOne({FirstName:"David",LastName:"Miller",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45265d93261e4bc9ea33")
}
> db.demo293.insertOne({FirstName:"John",LastName:"Smith",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45385d93261e4bc9ea34")
}
> db.demo293.insertOne({FirstName:"Adam",LastName:"Doe",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d46cf5d93261e4bc9ea35")
}

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

> db.demo293.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d45075d93261e4bc9ea32"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 }
{ "_id" : ObjectId("5e4d45265d93261e4bc9ea33"), "FirstName" : "David", "LastName" : "Miller", "Age" : 23 }
{ "_id" : ObjectId("5e4d45385d93261e4bc9ea34"), "FirstName" : "John", "LastName" : "Smith", "Age" : 24 }
{ "_id" : ObjectId("5e4d46cf5d93261e4bc9ea35"), "FirstName" : "Adam", "LastName" : "Doe", "Age" : 21 }

Following is the query to combine AND and OR −

> db.demo293.find( {
...   $and : [
...      {
...         $or : [
...            {"FirstName" : "John"},
...            {"LastName" : "Brown"}
...         ]
...      },
...      {
...         Age:24
...      }
...   ]
...} )

This will produce the following output −

{ "_id" : ObjectId("5e4d45075d93261e4bc9ea32"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 }
{ "_id" : ObjectId("5e4d45385d93261e4bc9ea34"), "FirstName" : "John", "LastName" : "Smith", "Age" : 24 }

Updated on: 31-Mar-2020

495 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements