0
0
MongoDBquery~5 mins

Boolean and null types in MongoDB

Choose your learning style9 modes available
Introduction

Boolean and null types help store simple true/false values and empty or missing information in your data.

To mark if a user is active or inactive with true or false.
To show if a task is completed or not using true or false.
To represent missing or unknown data with null.
To check if a field has no value in a document.
To filter documents based on true/false or null values.
Syntax
MongoDB
{ "fieldName": true | false | null }
Boolean values are either true or false without quotes.
Null means no value and is written as null without quotes.
Examples
This document field shows the user is active.
MongoDB
{ "isActive": true }
This field shows the task is not completed.
MongoDB
{ "isCompleted": false }
This field means the middle name is missing or unknown.
MongoDB
{ "middleName": null }
Sample Program

This example adds three tasks with different boolean and null values for completion. Then it finds only the tasks marked as completed (true).

MongoDB
db.tasks.insertMany([
  { "task": "Wash dishes", "isCompleted": false },
  { "task": "Do homework", "isCompleted": true },
  { "task": "Read book", "isCompleted": null }
])

// Find tasks that are completed
 db.tasks.find({ "isCompleted": true })
OutputSuccess
Important Notes

Boolean values are useful for yes/no or on/off states.

Null is different from false or empty string; it means no value at all.

When querying, use true, false, or null without quotes to match these types.

Summary

Boolean stores true or false values.

Null represents missing or unknown data.

Use these types to keep data clear and easy to check.