Tutorialspoint

1 Answer
Anvi Jain

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.