How to use or operator in MongoDB to fetch records on the basis of existence?


To fetch records with $or on the basis of existence, use $or along with $exists. Let us create a collection with documents −

>db.demo185.insertOne({_id:101,details:{Name:"Chris",Score:78,Subjects:{"Name":"MySQL"}}});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo185.insertOne({_id:102,details:{Name:"Bob",Score:78}});
{ "acknowledged" : true, "insertedId" : 102 }
>db.demo185.insertOne({_id:103,details:{Name:"David",Score:78,Subjects:{"Name":"MongoDB"}}});
{ "acknowledged" : true, "insertedId" : 103 }

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

> db.demo185.find();

This will produce the following output −

{ "_id" : 101, "details" : { "Name" : "Chris", "Score" : 78, "Subjects" : { "Name" : "MySQL" } } }
{ "_id" : 102, "details" : { "Name" : "Bob", "Score" : 78 } }
{ "_id" : 103, "details" : { "Name" : "David", "Score" : 78, "Subjects" : { "Name" : "MongoDB" } } }

Following is the query to use or operator in MongoDB −

> db.demo185.find({
...   "$or": [
...      { "details.Subjects.Name": { "$exists": true } },
...      { "details.Subjects.Name": { "$exists": true } }
...   ]
... })

This will produce the following output −

{ "_id" : 101, "details" : { "Name" : "Chris", "Score" : 78, "Subjects" : { "Name" : "MySQL" } } }
{ "_id" : 103, "details" : { "Name" : "David", "Score" : 78, "Subjects" : { "Name" : "MongoDB" } } }

Updated on: 27-Mar-2020

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements