Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

MongoDB Schema Validation

What is Schema Validation?

Although MongoDB is schema-flexible, you can enforce rules on documents using JSON Schema validation. This lets you require certain fields, restrict data types, set value ranges, and more — all enforced at the database level. Validation rules are defined using the $jsonSchema operator when creating or modifying a collection.

Creating a Collection with Validation

JSON Schema Validation with $jsonSchema
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age", "role"],
      additionalProperties: false,
      properties: {
        _id: { bsonType: "objectId" },
        name: {
          bsonType: "string",
          minLength: 2,
          maxLength: 100,
          description: "Name must be a string between 2 and 100 characters"
        },
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$",
          description: "Must be a valid email address"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 150,
          description: "Age must be an integer between 0 and 150"
        },
        role: {
          bsonType: "string",
          enum: ["admin", "editor", "user"],
          description: "Role must be one of: admin, editor, user"
        },
        active: {
          bsonType: "bool"
        },
        createdAt: {
          bsonType: "date"
        }
      }
    }
  },
  validationLevel: "strict",    // strict (default) or moderate
  validationAction: "error"     // error (default) or warn
})

validationLevel and validationAction

OptionValueBehavior
validationLevelstrictValidates all inserts and updates (default)
moderateValidates inserts and updates to documents that already pass validation; existing invalid documents are not re-validated
validationActionerrorRejects invalid documents with an error (default)
warnAllows invalid documents but logs a warning — useful during migration
Adding Validation to an Existing Collection
// Add or update validation rules on an existing collection
db.runCommand({
  collMod: "products",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["sku", "name", "price"],
      properties: {
        sku: { bsonType: "string" },
        name: { bsonType: "string" },
        price: {
          bsonType: "double",
          minimum: 0,
          description: "Price must be a non-negative number"
        },
        stock: {
          bsonType: "int",
          minimum: 0
        },
        tags: {
          bsonType: "array",
          items: { bsonType: "string" }
        }
      }
    }
  },
  validationLevel: "moderate",
  validationAction: "warn"
})

// View current validation rules
db.getCollectionInfos({ name: "products" })[0].options.validator
Validation Error Example
// This insert will FAIL — missing required "email" field
db.users.insertOne({ name: "Bob", age: NumberInt(25), role: "user" })
// MongoServerError: Document failed validation
// Details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [...] }

// This insert will FAIL — age out of range
db.users.insertOne({
  name: "Bob",
  email: "bob@example.com",
  age: NumberInt(200),   // exceeds maximum: 150
  role: "user"
})

// This insert will FAIL — invalid role enum value
db.users.insertOne({
  name: "Bob",
  email: "bob@example.com",
  age: NumberInt(25),
  role: "superuser"   // not in enum: ["admin", "editor", "user"]
})

// This insert will SUCCEED
db.users.insertOne({
  name: "Bob Smith",
  email: "bob@example.com",
  age: NumberInt(25),
  role: "user",
  active: true,
  createdAt: new Date()
})

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.