0
0
MongodbConceptBeginner · 3 min read

Boolean Type in MongoDB: Definition and Usage

In MongoDB, the boolean type represents a value that can be either true or false. It is used to store simple yes/no or on/off states within documents. This type helps in filtering and querying data based on binary conditions.
⚙️

How It Works

The boolean type in MongoDB is like a simple switch that can be either on or off, represented by true or false. Imagine a light bulb that is either lit or not lit; similarly, a boolean field in a MongoDB document holds one of these two states.

This type is stored efficiently and is easy to check when you want to filter documents. For example, you might have a field called isActive to show if a user account is active (true) or inactive (false).

When you query MongoDB, you can ask for documents where the boolean field matches your condition, making it very useful for simple decision-making data.

💻

Example

This example shows how to insert a document with a boolean field and then query documents where that field is true.

mongodb
db.users.insertOne({ name: "Alice", isActive: true })
db.users.insertOne({ name: "Bob", isActive: false })
db.users.find({ isActive: true })
Output
{ "_id": ObjectId("...") , "name": "Alice", "isActive": true }
🎯

When to Use

Use the boolean type when you need to store simple yes/no, true/false, or on/off information in your documents. It is perfect for flags like isVerified, hasPaid, or isAdmin.

For example, an online store might use a boolean to track if a product is in stock or if a user has accepted terms and conditions. This helps keep your data clear and your queries fast.

Key Points

  • The boolean type stores only true or false.
  • It is useful for simple binary states or flags.
  • Boolean fields make filtering and querying straightforward.
  • Use it to represent yes/no or on/off conditions in your data.

Key Takeaways

The boolean type in MongoDB stores true or false values for simple binary states.
Use boolean fields to represent flags like active status or verification.
Boolean values make querying documents based on yes/no conditions easy and efficient.