- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 Query to combine AND & OR?
To combine AND & OR in MongoDB, let us first create a collection with documents −
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentSkill":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd306dcb64f4b851c3a13e2") } >db.combinedAndOrDemo.insertOne({"StudentFirstName":"Larry","StudentAge":21,"StudentSkill":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd306f3b64f4b851c3a13e3") } >db.combinedAndOrDemo.insertOne({"StudentFirstName":"Sam","StudentAge":24,"StudentSkill":"SQL Server"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd30701b64f4b851c3a13e4") }
Following is the query to display all documents from a collection with the help of find() method −
> db.combinedAndOrDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" } { "_id" : ObjectId("5cd306f3b64f4b851c3a13e3"), "StudentFirstName" : "Larry", "StudentAge" : 21, "StudentSkill" : "MySQL" } { "_id" : ObjectId("5cd30701b64f4b851c3a13e4"), "StudentFirstName" : "Sam", "StudentAge" : 24, "StudentSkill" : "SQL Server" }
Following is the query for combined AND & OR −
> db.combinedAndOrDemo.find( {"$or":[ {"$and": [{"StudentFirstName": "John"}, {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}] }, {"StudentSkill" : "MongoDB" } ] } );
This will produce the following output −
{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" }
- Related Articles
- MongoDB aggregation to combine or merge fields and then count?
- Combine update and query parts to form the upserted document in MongoDB?
- How to implement MongoDB $or query?
- MongoDB query to implement OR operator in find()
- MongoDB query which represents not equal to null or empty?
- MongoDB query to get documents with multiple conditions set in $or?
- MongoDB query to select distinct and count?
- MongoDB query with an 'or' condition?\n
- Fetch multiple documents in MongoDB query with OR condition?
- MongoDB query to find on the basis of true or false values
- MongoDB query to store File Name and location?
- MySQL query to combine two columns in a single column?
- Can I query on a MongoDB index if my query contains the $or operator?
- MongoDB query to skip documents
- MongoDB query to sort subdocuments

Advertisements