MongoDB Query for boolean field as “not true”

MongoDBDatabaseBig Data Analytics

You can use $ne(not equal) operator for this. The syntax is as follows −

db.yourCollectionName.find({yourFieldName: {$ne: true}}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Larry","EmployeeAge":24,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f7680f10143d8431e13")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Mike","EmployeeAge":20,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f8680f10143d8431e14")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Sam","EmployeeAge":23,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f9380f10143d8431e15")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"David","EmployeeAge":25,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fa280f10143d8431e16")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Carol","EmployeeAge":27,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fae80f10143d8431e17")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.queryForBooleanFieldsDemo.find().pretty();

The following is the output −

{
   "_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
}

Here is the query for the boolean field as “not true” −

> db.queryForBooleanFieldsDemo.find({isOldEmployee: {$ne: true}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8b7f8680f10143d8431e14"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : 20,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7f9380f10143d8431e15"),
   "EmployeeName" : "Sam",
   "EmployeeAge" : 23,
   "isOldEmployee" : false
}
raja
Published on 29-Mar-2019 15:47:01
Advertisements