#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Defining validation rules using JSON Schema for data integrity

Schema Validation

MongoDB's schema is flexible by default — but flexibility without guardrails can lead to inconsistent data. Schema validation lets you enforce structure and data integrity using JSON Schema, without giving up MongoDB's flexibility entirely.

1. Why Validate?

  • Prevent malformed documents (missing required fields, wrong types)
  • Catch bugs early — at the database layer, not just the application layer
  • Document your schema intentions directly in the database

2. Creating a Collection with Validation

db.createCollection("employees", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "department"],
      properties: {
        name: { bsonType: "string", description: "must be a string and is required" },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "must be a valid email address"
        },
        department: {
          enum: ["Engineering", "Sales", "HR", "Marketing"],
          description: "must be one of the enum values"
        },
        age: {
          bsonType: "int",
          minimum: 18,
          maximum: 65,
          description: "must be an integer between 18 and 65"
        }
      }
    }
  }
})

3. Validation Levels and Actions

OptionValuesEffect
validationLevel"strict" (default) / "moderate"Strict validates all writes; moderate skips existing invalid documents
validationAction"error" (default) / "warn"Error rejects invalid writes; warn logs but allows them

4. Adding Validation to an Existing Collection

db.runCommand({
  collMod: "employees",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"]
    }
  },
  validationLevel: "moderate"
})
Common Issue: Applying strict validation to a collection with existing "bad" documents will block future updates to those documents unless you use validationLevel: "moderate".

5. Testing Validation

// This insert fails validation (missing required "department")
db.employees.insertOne({ name: "Kabir Singh", email: "kabir@example.com" })

// MongoServerError: Document failed validation

6. Schema Validation Checklist

  • ✅ Define required fields and types with $jsonSchema
  • ✅ Use enum for restricted value sets
  • ✅ Choose validationLevel and validationAction appropriately
  • ✅ Apply validation to existing collections with collMod
Key Takeaway: Schema validation gives you the best of both worlds — MongoDB's flexibility during development, with the safety of enforced structure as your application matures.

Ready to master MongoDB?

Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.

Explore Course