MongoDB Validation

Ensure data quality with schema validation rules

✅ What is Schema Validation?

MongoDB schema validation enforces data structure and type rules at the database level. It ensures documents meet specific requirements before insertion or update, maintaining data integrity and consistency.


// Basic validation example
db.createCollection("users", {
  validator: { $jsonSchema: { 
    required: ["name", "email"],
    properties: { email: { bsonType: "string" } }
  }}
})
                                    

Result:

Collection created with validation rules enforced

Key Validation Features

📋

JSON Schema

Standard validation syntax

{ $jsonSchema: { bsonType: "object" } }
🔒

Required Fields

Enforce mandatory fields

{ required: ["name", "email"] }
🎯

Type Checking

Validate data types

{ bsonType: "string" }
📏

Range Validation

Set min/max values

{ minimum: 0, maximum: 100 }

🔹 Creating Validation Rules

Define validation rules when creating a collection or add them later. Use JSON Schema syntax to specify field requirements, data types, and constraints for your documents.

// Create collection with validation
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "price", "category"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        price: {
          bsonType: "number",
          minimum: 0,
          description: "must be a positive number"
        },
        category: {
          enum: ["Electronics", "Clothing", "Books"],
          description: "must be one of the enum values"
        }
      }
    }
  }
})

Result:

Collection created with strict validation rules

🔹 Data Type Validation

MongoDB supports various BSON types for validation including string, number, boolean, date, array, and object. Specify exact types to ensure data consistency across documents.

// Validate different data types
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      properties: {
        username: { bsonType: "string" },
        age: { bsonType: "int" },
        email: { bsonType: "string" },
        isActive: { bsonType: "bool" },
        createdAt: { bsonType: "date" },
        tags: { 
          bsonType: "array",
          items: { bsonType: "string" }
        },
        address: {
          bsonType: "object",
          properties: {
            street: { bsonType: "string" },
            city: { bsonType: "string" }
          }
        }
      }
    }
  }
})

Supported Types:

string, int, double, bool, date, array, object, null, objectId

🔹 String Validation

Apply specific constraints to string fields including pattern matching with regex, minimum and maximum length requirements, and enumerated allowed values for controlled vocabularies.

// String validation with patterns and length
db.createCollection("accounts", {
  validator: {
    $jsonSchema: {
      properties: {
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
          description: "must be a valid email format"
        },
        username: {
          bsonType: "string",
          minLength: 3,
          maxLength: 20,
          description: "must be 3-20 characters"
        },
        status: {
          enum: ["active", "inactive", "pending"],
          description: "must be one of the allowed values"
        },
        phone: {
          bsonType: "string",
          pattern: "^\\d{10}$",
          description: "must be 10 digits"
        }
      }
    }
  }
})

Result:

Strings validated for format, length, and allowed values

🔹 Number Validation

Set numeric constraints including minimum and maximum values, multiple-of requirements for specific increments, and exclusive boundaries for precise range control in your numeric fields.

// Number validation with ranges
db.createCollection("orders", {
  validator: {
    $jsonSchema: {
      properties: {
        quantity: {
          bsonType: "int",
          minimum: 1,
          maximum: 1000,
          description: "must be between 1 and 1000"
        },
        price: {
          bsonType: "double",
          minimum: 0,
          exclusiveMinimum: true,
          description: "must be greater than 0"
        },
        discount: {
          bsonType: "number",
          minimum: 0,
          maximum: 100,
          multipleOf: 5,
          description: "must be 0-100 in increments of 5"
        }
      }
    }
  }
})

Result:

Numbers validated for range and precision

🔹 Array and Object Validation

Validate complex nested structures by defining rules for arrays and embedded objects. Control array length, item types, and nested object properties for comprehensive data validation.

// Validate arrays and nested objects
db.createCollection("posts", {
  validator: {
    $jsonSchema: {
      properties: {
        tags: {
          bsonType: "array",
          minItems: 1,
          maxItems: 5,
          uniqueItems: true,
          items: { bsonType: "string" }
        },
        author: {
          bsonType: "object",
          required: ["name", "email"],
          properties: {
            name: { bsonType: "string" },
            email: { bsonType: "string" }
          }
        },
        comments: {
          bsonType: "array",
          items: {
            bsonType: "object",
            required: ["text", "user"],
            properties: {
              text: { bsonType: "string" },
              user: { bsonType: "string" },
              date: { bsonType: "date" }
            }
          }
        }
      }
    }
  }
})

Result:

Complex nested structures validated successfully

🔹 Validation Actions and Levels

Control how MongoDB handles validation failures with different actions (error or warn) and validation levels (strict or moderate) to balance data quality with flexibility.

// Set validation action and level
db.createCollection("logs", {
  validator: { $jsonSchema: { /* rules */ } },
  validationAction: "warn",  // or "error" (default)
  validationLevel: "moderate" // or "strict" (default)
})

// Update validation rules
db.runCommand({
  collMod: "logs",
  validator: { $jsonSchema: { /* new rules */ } },
  validationAction: "error",
  validationLevel: "strict"
})

// Validation Actions:
// - "error": Reject invalid documents (default)
// - "warn": Allow but log invalid documents

// Validation Levels:
// - "strict": Validate all inserts and updates (default)
// - "moderate": Validate inserts and updates to valid docs

Result:

Validation behavior configured as specified

🔹 Practical Example

Complete user registration system with comprehensive validation including email format, password strength, age restrictions, and profile completeness checks.

// Complete validation example for user registration
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email", "password", "age"],
      properties: {
        username: {
          bsonType: "string",
          minLength: 3,
          maxLength: 20,
          pattern: "^[a-zA-Z0-9_]+$"
        },
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
        },
        password: {
          bsonType: "string",
          minLength: 8
        },
        age: {
          bsonType: "int",
          minimum: 13,
          maximum: 120
        },
        role: {
          enum: ["user", "admin", "moderator"]
        }
      }
    }
  },
  validationAction: "error"
})

// Valid insert
db.users.insertOne({
  username: "john_doe",
  email: "[email protected]",
  password: "securePass123",
  age: 25,
  role: "user"
}) // ✅ Success

// Invalid insert
db.users.insertOne({
  username: "ab",  // Too short
  email: "invalid-email",
  age: 10  // Too young
}) // ❌ Validation Error

Output:

Valid documents accepted, invalid documents rejected with error messages

🧠 Test Your Knowledge

What happens when validationAction is set to "warn"?