MongoDB query to find on the basis of true or false values


To find on the basis of true or false values, use $exists in find(). You would also need dot notation for the same task.

Let us first create a collection with documents −

> db.demo367.insertOne(
...    { "Id" : "102",
...    "details" : [ { "Name" : "David"},
...    { "Age" : 23, "CountryName" : "UK"} ],
...    "isMarried" : false }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e0b62ae06a1609a00ae8")
}
> db.demo367.insertOne(
...    { "Id" : "101",
...    "details" : [ { "Name" : "Chris", "Subject" : [ "MySQL" ] },
...    { "Age" : 21, "CountryName" : "US"} ],
...    "isMarried" : true }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e0be2ae06a1609a00ae9")
}

Display all documents from a collection with the help of find() method −

> db.demo367.find();

This will produce the following output −

{
   "_id" : ObjectId("5e57e0b62ae06a1609a00ae8"), "Id" : "102", "details" : [
      { "Name" : "David" }, { "Age" : 23, "CountryName" : "UK" } ], "isMarried" : false }
{
   "_id" : ObjectId("5e57e0be2ae06a1609a00ae9"), "Id" : "101", "details" : [
      { "Name" : "Chris", "Subject" : [ "MySQL" ] }, { "Age" : 21, "CountryName" : "US" } ], "isMarried" : true 
}

Following is the query to find on the basis of true false values by checking with $exists −

> db.demo367.find({"details.Subject": { $exists: false}});

This will produce the following output −

{ "_id" : ObjectId("5e57e0b62ae06a1609a00ae8"), "Id" : "102", "details" : [ { "Name" : "David" }, { "Age" : 23, "CountryName" : "UK" } ], "isMarried" : false }

Updated on: 02-Apr-2020

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements