What is the syntax for boolean values in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $eq as well as $ne operator for boolean values. Let us first create a collection with documents −

> db.booleanQueryDemo.insertOne({"UserName":"John","UserAge":23,"isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc815c08f9e6ff3eb0ce44a")
}
> db.booleanQueryDemo.insertOne({"UserName":"Chris","UserAge":21,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc815d08f9e6ff3eb0ce44b")
}
> db.booleanQueryDemo.insertOne({"UserName":"Robert","UserAge":24,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc815dc8f9e6ff3eb0ce44c")
}
> db.booleanQueryDemo.insertOne({"UserName":"David","UserAge":26,"isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc815ed8f9e6ff3eb0ce44d")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc815c08f9e6ff3eb0ce44a"),
   "UserName" : "John",
   "UserAge" : 23,
   "isMarried" : true
}
{
   "_id" : ObjectId("5cc815d08f9e6ff3eb0ce44b"),
   "UserName" : "Chris",
   "UserAge" : 21,
   "isMarried" : false
}
{
   "_id" : ObjectId("5cc815dc8f9e6ff3eb0ce44c"),
   "UserName" : "Robert",
   "UserAge" : 24,
   "isMarried" : false
}
{
   "_id" : ObjectId("5cc815ed8f9e6ff3eb0ce44d"),
   "UserName" : "David",
   "UserAge" : 26,
   "isMarried" : true
}

Case 1 − When the value is equal to false.

Following is the query for boolean values −

> db.booleanQueryDemo.find({isMarried: {$eq: false}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc815d08f9e6ff3eb0ce44b"),
   "UserName" : "Chris",
   "UserAge" : 21,
   "isMarried" : false
}
{
   "_id" : ObjectId("5cc815dc8f9e6ff3eb0ce44c"),
   "UserName" : "Robert",
   "UserAge" : 24,
   "isMarried" : false
}

Case 2 − When the value is equal to true.

Following is the query −

> db.booleanQueryDemo.find({isMarried: {$ne: false}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc815c08f9e6ff3eb0ce44a"),
   "UserName" : "John",
   "UserAge" : 23,
   "isMarried" : true
}
{
   "_id" : ObjectId("5cc815ed8f9e6ff3eb0ce44d"),
   "UserName" : "David",
   "UserAge" : 26,
   "isMarried" : true
}
raja
Published on 21-May-2019 15:54:49
Advertisements