- 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 implement MongoDB $or operator
Evaluate one or more expressions using the $or operator in MongoDB. Following is the syntax −
db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty();
Let us first create a collection with documents −
> db.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b80a6d78f205348bc61b") } > db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8266d78f205348bc61c") } > db.orOperatorDemo.insertOne({"StudentNames":["John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8346d78f205348bc61d") }
Following is the query to display all documents from a collection with the help of find() method −
> db.orOperatorDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8266d78f205348bc61c"), "StudentNames" : [ "Robert", "Chris", "David" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }
Here is the query to $or operator syntax −
> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }
Advertisements