- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } } }
Advertisements