
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
MongoDB Query to Exclude Both Fields with False
Use $or operator along with $expr operator for this. Let us first create a collection with documents, wherein one of fields is isMarried having true of false value −
> db.orTwoFieldsDemo.insertOne({"isLiveInUS":true,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cdfd86abf3115999ed5120d") } > db.orTwoFieldsDemo.insertOne({"isLiveInUS":true,"isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5cdfd876bf3115999ed5120e") } > db.orTwoFieldsDemo.insertOne({"isLiveInUS":false,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cdfd87dbf3115999ed5120f") }
Following is the query to display all documents from a collection with the help of find() method −
> db.orTwoFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdfd86abf3115999ed5120d"), "isLiveInUS" : true, "isMarried" : false } { "_id" : ObjectId("5cdfd876bf3115999ed5120e"), "isLiveInUS" : true, "isMarried" : true } { "_id" : ObjectId("5cdfd87dbf3115999ed5120f"), "isLiveInUS" : false, "isMarried" : false }
Following is the query to avoid both the FALSE values in two fields and display only fields with TRUE or one of the field with TRUE or another FALSE vice-versa −
> db.orTwoFieldsDemo.find({ $expr: { $or: [ "$isLiveInUS", "$isMarried" ] } });
This will produce the following output −
{ "_id" : ObjectId("5cdfd86abf3115999ed5120d"), "isLiveInUS" : true, "isMarried" : false } { "_id" : ObjectId("5cdfd876bf3115999ed5120e"), "isLiveInUS" : true, "isMarried" : true }
Advertisements