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 for boolean field as "not true
You can use the $ne (not equal) operator to query for boolean fields that are "not true". This operator returns documents where the field value is either false or does not exist.
Syntax
db.collectionName.find({
fieldName: { $ne: true }
});
Sample Data
Let us create a collection with employee documents to demonstrate the query ?
db.queryForBooleanFieldsDemo.insertMany([
{ "EmployeeName": "Larry", "EmployeeAge": 24, "isOldEmployee": true },
{ "EmployeeName": "Mike", "EmployeeAge": 20, "isOldEmployee": false },
{ "EmployeeName": "Sam", "EmployeeAge": 23, "isOldEmployee": false },
{ "EmployeeName": "David", "EmployeeAge": 25, "isOldEmployee": true },
{ "EmployeeName": "Carol", "EmployeeAge": 27, "isOldEmployee": true }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8b7f7680f10143d8431e13"),
ObjectId("5c8b7f8680f10143d8431e14"),
ObjectId("5c8b7f9380f10143d8431e15"),
ObjectId("5c8b7fa280f10143d8431e16"),
ObjectId("5c8b7fae80f10143d8431e17")
]
}
Display all documents to verify the data ?
db.queryForBooleanFieldsDemo.find().pretty();
{
"_id": ObjectId("5c8b7f7680f10143d8431e13"),
"EmployeeName": "Larry",
"EmployeeAge": 24,
"isOldEmployee": true
}
{
"_id": ObjectId("5c8b7f8680f10143d8431e14"),
"EmployeeName": "Mike",
"EmployeeAge": 20,
"isOldEmployee": false
}
{
"_id": ObjectId("5c8b7f9380f10143d8431e15"),
"EmployeeName": "Sam",
"EmployeeAge": 23,
"isOldEmployee": false
}
{
"_id": ObjectId("5c8b7fa280f10143d8431e16"),
"EmployeeName": "David",
"EmployeeAge": 25,
"isOldEmployee": true
}
{
"_id": ObjectId("5c8b7fae80f10143d8431e17"),
"EmployeeName": "Carol",
"EmployeeAge": 27,
"isOldEmployee": true
}
Example: Query for "Not True" Boolean Field
Find all employees where isOldEmployee is not true ?
db.queryForBooleanFieldsDemo.find({
isOldEmployee: { $ne: true }
}).pretty();
{
"_id": ObjectId("5c8b7f8680f10143d8431e14"),
"EmployeeName": "Mike",
"EmployeeAge": 20,
"isOldEmployee": false
}
{
"_id": ObjectId("5c8b7f9380f10143d8431e15"),
"EmployeeName": "Sam",
"EmployeeAge": 23,
"isOldEmployee": false
}
Key Points
- The
$neoperator matches documents where the field value is not equal to the specified value. - For boolean fields,
{ $ne: true }returns documents withfalsevalues or missing fields. - Alternative approaches include
{ fieldName: false }for exact false matches.
Conclusion
Use the $ne operator with true to query boolean fields that are "not true". This approach effectively filters documents where the boolean field is either false or undefined.
Advertisements
