
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement MongoDB OR Query
The syntax is as follows for the $or query in MongoDB −
db.yourCollectionName.find({ $or : [ { "yourFieldName" : "yourValue1" }, {"yourFieldName":"yourValue2"},...........N ] } ).pretty();
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.orDemo.insertOne({"UserName":"Larry","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9491fd4cf1f7a64fa4df4c") } > db.orDemo.insertOne({"UserName":"David","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c9492074cf1f7a64fa4df4d") } > db.orDemo.insertOne({"UserName":"Mike","UserAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c94920e4cf1f7a64fa4df4e") } > db.orDemo.insertOne({"UserName":"Sam","UserAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c9492144cf1f7a64fa4df4f") } > db.orDemo.insertOne({"UserName":"Carol","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c94921d4cf1f7a64fa4df50") } > db.orDemo.insertOne({"UserName":"Bob","UserAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c94922c4cf1f7a64fa4df51") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.orDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"), "UserName" : "Larry", "UserAge" : 23 } { "_id" : ObjectId("5c9492074cf1f7a64fa4df4d"), "UserName" : "David", "UserAge" : 21 } { "_id" : ObjectId("5c94920e4cf1f7a64fa4df4e"), "UserName" : "Mike", "UserAge" : 25 } { "_id" : ObjectId("5c9492144cf1f7a64fa4df4f"), "UserName" : "Sam", "UserAge" : 20 } { "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"), "UserName" : "Carol", "UserAge" : 24 } { "_id" : ObjectId("5c94922c4cf1f7a64fa4df51"), "UserName" : "Bob", "UserAge" : 22 }
Here is the query for $or −
> db.orDemo.find({ $or : [ { "UserName" : "Carol" }, {"UserName":"Larry"} ] } ).pretty();
The following is the output:
{ "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"), "UserName" : "Larry", "UserAge" : 23 } { "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"), "UserName" : "Carol", "UserAge" : 24 }
Advertisements