MongoDB Schema Validation

MongoDB Tutorial

MongoDB Schema Validation 🛡️📐

In MongoDB, Schema Validation lets you enforce rules on documents inside a collection—while still keeping MongoDB’s flexible schema nature.

It helps prevent bad/invalid data from being inserted or updated.


Why Schema Validation?

  • Ensure data consistency

  • Catch invalid inserts/updates

  • Enforce required fields & data types

  • Safer for large teams & production apps

📌 Validation is applied at the collection level.


Ways to Define Schema Validation

MongoDB supports:

  1. JSON Schema ($jsonSchema) ✅ (Know this)

  2. Query Expression Validators (older style)

👉 Prefer JSON Schema (clear & standard).


1️⃣ Create Collection with Schema Validation (JSON Schema)

Example: students collection

db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age", "course"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 60,
description: "must be an integer between 18 and 60"
},
course: {
bsonType: "string",
enum: ["BA", "BSc", "BCom"],
description: "allowed values only"
}
}
}
}
})

✅ Collection created with validation rules.


2️⃣ Insert Valid Document ✅

db.students.insertOne({
name: "Amit",
age: 22,
course: "BA"
})

✔ Insert succeeds.


3️⃣ Insert Invalid Document ❌

db.students.insertOne({
name: "Rahul",
age: 15,
course: "MBA"
})

❌ Fails due to:

  • age < 18

  • course not allowed


4️⃣ Validation Levels

validationLevel

  • strict (default) → validate all inserts & updates

  • moderate → validate only new/updated fields

validationLevel: "moderate"

5️⃣ Validation Actions

validationAction

  • error (default) → reject invalid data

  • warn → allow insert but log warning

validationAction: "warn"

6️⃣ Modify Validation on Existing Collection

db.runCommand({
collMod: "students",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
age: {
bsonType: "int",
minimum: 18
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})

7️⃣ Schema Validation Using Query Expressions (Alternative)

db.createCollection("employees", {
validator: {
age: { $gte: 18 }
}
})

⚠️ Less readable than JSON Schema.


MongoDB vs SQL Schema

SQLMongoDB
Strict schemaFlexible schema
Defined in tableDefined via validator
ALTER TABLEcollMod

Best Practices 👍

  • Use schema validation in production

  • Start with moderate, move to strict

  • Combine with indexes

  • Validate only critical fields


Common Mistakes ❌

  • Forgetting bsonType (use BSON types, not JS types)

  • Over-validating (kills flexibility)

  • Expecting validation to fix old data


Quick Recap 🧠

$jsonSchema // schema rules
required // mandatory fields
bsonType // data types
validationLevel // strict / moderate
validationAction // error / warn

You may also like...