- Trending Categories
- 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 multiple OR conditions on same key?
For this, simply use $or once. Let us create a collection with documents −
> db.demo551.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36d39e5f92834d7f05e5") } > db.demo551.insertOne({"Name":"Chris Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36d89e5f92834d7f05e6") } > db.demo551.insertOne({"Name":"John Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36de9e5f92834d7f05e7") } > db.demo551.insertOne({"Name":"John Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36e59e5f92834d7f05e8") } > db.demo551.insertOne({"Name":"Carol"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36ec9e5f92834d7f05e9") }
Display all documents from a collection with the help of find() method −
> db.demo551.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" } { "_id" : ObjectId("5e8e36d89e5f92834d7f05e6"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e8e36de9e5f92834d7f05e7"), "Name" : "John Doe" } { "_id" : ObjectId("5e8e36e59e5f92834d7f05e8"), "Name" : "John Smith" } { "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }
Following is the query to implement OR conditions on the same key −
> db.demo551.find({$or:[ ... {"Name" : {$eq : "Carol"}}, ... {Name: {$eq:"John"}} ... ] ... });
This will produce the following output −
{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" } { "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }
Advertisements