Schema Validation in MongoDB

From the MongoDB cheat sheet ยท Schema Design & Validation ยท verified Jul 2026

Schema Validation

Enforce document structure and data types

javascript
// Create collection with validation
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string"
        },
        email: {
          bsonType: "string",
          pattern: "^[a-z0-9+_.-]+@[a-z0-9.-]+$"
        },
        age: {
          bsonType: "int",
          minimum: 18,
          maximum: 120
        }
      }
    }
  }
})
๐ŸŸข Essential - Ensure data integrity
๐Ÿ’ก JSON Schema provides rich validation
๐Ÿ“Œ validationLevel controls when to validate
โš ๏ธ Validation adds small performance overhead
๐Ÿ”— Related: Mongoose for application-level validation
schemavalidation

More MongoDB tasks

Back to the full MongoDB cheat sheet