MongoDB โ€” Schema Validation & JSON Schema

๐Ÿƒ MongoDB 7.0+ ๐ŸŸข Chapter 25 of 50 ๐Ÿ“‚ Phase 05: Array Updates, Upserts & Deletions ๐Ÿ“… 2026 Edition

Enforce database-level validation rules using JSON Schema ($jsonSchema) and collMod commands.

1Enforcing Schema Rules with $jsonSchema
createCollection with Validation
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name: { bsonType: "string", description: "Must be a string" },
        email: { pattern: "^.+@.+$", description: "Must be a valid email" },
        age: { bsonType: "int", minimum: 18, description: "Must be an integer >= 18" }
      }
    }
  },
  validationAction: "error"
});
2Modifying Validation Rules on Existing Collections
collMod Command Example
// Modify validation rules without recreating collection
db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "status"]
    }
  },
  validationLevel: "moderate"
});
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on MongoDB 7.0+ Standards ยท Last updated August 2026