Boolean data type in MongoDB: Tutorial & Examples

Updated: February 2, 2024 By: Guest Contributor Post a comment

Introduction to Boolean Data Type in MongoDB

Boolean data type represents one of the simplest forms of data – true or false. In MongoDB, a document-oriented NoSQL database, booleans are fundamental data type used for flagging, conditional checks, and control flow in data structures. Understanding how to work with booleans is essential for effective database queries and application logic.

In this tutorial, we will explore the Boolean data type in MongoDB with practical examples. Starting with the basics, we’ll progress to more advanced use cases to give you a comprehensive understanding of how booleans are used within MongoDB.

Basic Usage – Creating Documents with Boolean Fields

// Connect to a MongoDB database and insert a document with a boolean field
db.collection('products').insertOne({
  name: 'LED Light',
  inStock: true
});

Output:

{
  "acknowledged": true,
  "insertedId": "..."
}

The inStock field now stores a boolean value indicating the availability of the product.

Querying Documents with Boolean Fields

// Fetch documents where the 'inStock' field is true
const availableProducts = db.collection('products').find({ inStock: true }).toArray();
console.log(availableProducts);

Output:

[{
  "_id": "...",
  "name": "LED Light",
  "inStock": true
}]

This query returns all documents within the ‘products’ collection that are currently in stock.

Updating Documents Using Booleans

// Update the 'inStock' field from true to false for a product.
db.collection('products').updateOne({
  name: 'LED Light'
}, {
  $set: { inStock: false }
});

Output:

{
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1
}

The specified document’s inStock field has been updated to false.

Advanced Queries with Boolean Logic

MongoDB allows users to perform more sophisticated queries using boolean operators such as $and, $or, and $not.

// Find products that are either out of stock or with a price greater than 20
const query = {
  $or: [{ inStock: false }, { price: { $gt: 20 } }]
};
db.collection('products').find(query).toArray()
  .then(products => console.log(products));

Output:

[{
  "_id": "...",
  "name": "LED Light",
  "inStock": false,
  "price": 18
}, {
  "_id": "...",
  "name": "Solar Panel",
  "inStock": false,
  "price": 24
}]

The above query uses the $or operator to find documents that satisfy at least one of the conditions.

Using Booleans for Schema Validation

Understanding the role boolean values play in schema validation is important for maintaining data integrity within a MongoDB collection.

The example below covers creating a collection with schema validation that enforces the inStock field to be a boolean, demonstrating the importance of boolean values in maintaining data integrity:

// Connect to MongoDB using the mongo shell or your preferred MongoDB driver/language

// Step 1: Create a new collection with schema validation
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "inStock"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        inStock: {
          bsonType: "bool",
          description: "must be a boolean and is required"
        }
      }
    }
  },
  validationLevel: "strict", // Ensures all documents adhere to the schema
  validationAction: "error" // MongoDB will throw an error for any violations
});

// Step 2: Insert a document into the collection
// This insertion will succeed because it adheres to the schema
db.products.insertOne({
  name: "Laptop",
  inStock: true
});

// Step 3: Attempt to insert a document that violates the schema
// This insertion will fail because 'inStock' is not a boolean
db.products.insertOne({
  name: "Smartphone",
  inStock: "yes" // Incorrect type
});

// MongoDB will throw an error for the second insertion attempt, 
// indicating that the 'inStock' field must be a boolean as defined by the schema.

Handling Nulls and Undefined Fields

Special care must be taken when dealing with null and undefined values in documents, as they can behave differently than false — explicitly handling these can avoid potential logical issues in queries.

Example:

// Connect to MongoDB

// Step 1: Insert sample documents with various states for the 'available' field
db.inventory.insertMany([
  { item: "journal", available: null }, // Explicitly set to null
  { item: "notebook", available: undefined }, // Will not store 'available' field
  { item: "paper", available: false }, // Explicitly set to false
  { item: "planner" }, // Does not include the 'available' field, similar to undefined
  { item: "postcard", available: true } // Explicitly set to true
]);

// Step 2: Query to find documents where 'available' is explicitly set to null
db.inventory.find({ available: null });

// Step 3: Query to find documents where 'available' field does not exist
db.inventory.find({ available: { $exists: false } });

// Note: The first query will return items with 'available' set to null and those without the 'available' field.
// The second query finds documents without the 'available' field, including those with 'available' set to undefined.

Boolean Aggregation Operators

MongoDB’s aggregation pipeline offers boolean operators to control logic flows within complex analytical queries and data processing tasks.

// Using boolean aggregation operators to count in-stock vs out-of-stock products
db.collection('products').aggregate([
      {
        $group: {
          _id: "$inStock",
          count: { $sum: 1 }
        }
      }
    ])
    .toArray()
    .then(result => console.log(result));

Output:

[{
  "_id": true,
  "count": 423
}, {
  "_id": false,
  "count": 85
}]

This aggregation counts how many products are in stock versus how many are not, using the boolean field for grouping.

To improve the performance of queries filtering on boolean fields, creating indexes on those fields can be beneficial.

Conclusion

To wrap up, booleans are a powerful and straightforward data type in MongoDB. Whether you’re controlling document structure, querying, or performing complex aggregations, understanding booleans will help you create more efficient and effective database applications. With the examples provided, you now have a fundamental to advanced toolbox to leverage the boolean data type in MongoDB.