Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to find on the basis of true or false values
To find documents based on true or false values in MongoDB, use the $exists operator with dot notation to check field presence or use direct boolean value matching.
Syntax
db.collection.find({"field": { $exists: true/false }});
db.collection.find({"booleanField": true/false});
Sample Data
db.demo367.insertMany([
{
"Id": "102",
"details": [
{ "Name": "David" },
{ "Age": 23, "CountryName": "UK" }
],
"isMarried": false
},
{
"Id": "101",
"details": [
{ "Name": "Chris", "Subject": ["MySQL"] },
{ "Age": 21, "CountryName": "US" }
],
"isMarried": true
}
]);
Method 1: Using $exists to Check Field Presence
Find documents where the nested "Subject" field does not exist ?
db.demo367.find({"details.Subject": { $exists: false }});
{
"_id": ObjectId("5e57e0b62ae06a1609a00ae8"),
"Id": "102",
"details": [
{ "Name": "David" },
{ "Age": 23, "CountryName": "UK" }
],
"isMarried": false
}
Method 2: Direct Boolean Value Matching
Find documents where "isMarried" is true ?
db.demo367.find({"isMarried": true});
{
"_id": ObjectId("5e57e0be2ae06a1609a00ae9"),
"Id": "101",
"details": [
{ "Name": "Chris", "Subject": ["MySQL"] },
{ "Age": 21, "CountryName": "US" }
],
"isMarried": true
}
Key Points
-
$exists: falsefinds documents where the specified field is missing -
$exists: truefinds documents where the specified field is present - Use dot notation for nested field queries
- Direct boolean matching queries the actual field value
Conclusion
Use $exists to check field presence and direct boolean matching to query true/false values. Combine with dot notation for nested field queries in complex document structures.
Advertisements
