- 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
MongoDB to fetch documents with $or Operator
The $or operator performs a logical OR operation on an array of two or more expressions. Let us create a collection with documents −
> db.demo674.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3f33604263e90dac943eb") } > db.demo674.insertOne({Name:"David",Age:23}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3f33c04263e90dac943ec") } > db.demo674.insertOne({Name:"Bob",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3f34204263e90dac943ed") } > db.demo674.insertOne({Name:"John",Age:24}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3f34804263e90dac943ee") }
Display all documents from a collection with the help of find() method −
> db.demo674.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 } { "_id" : ObjectId("5ea3f34804263e90dac943ee"), "Name" : "John", "Age" : 24 }
Following is the query to fetch documents with $or operator −
> db.demo674.find({$or:[{Name:"David"},{Age:21}]});
This will produce the following output −
{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 }
Advertisements