MongoDB Validation

Schema validation lets MongoDB enforce rules about the shape and content of documents in a collection, even though MongoDB is schema-less by default.

Why Validate Documents

MongoDB's flexibility means any document, with any fields, can normally be inserted into a collection. That flexibility is powerful during early development, but as an application matures you usually want guarantees: a user document must have an email, an age field must be a positive number, a status field must be one of a fixed set of values. Schema validation adds those guarantees at the database level, so bad data is rejected before it is ever written.

Validation rules are expressed using $jsonSchema, a MongoDB implementation of the JSON Schema standard. You attach the rules to a collection, either when you create it or by updating an existing collection with collMod.

Creating a Collection with Validation

The validator option on createCollection defines the rules. required lists mandatory fields, properties describes the type and constraints for each field.

Create a validated collection

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name: { bsonType: "string", description: "must be a string" },
        email: { bsonType: "string", pattern: "^.+@.+$" },
        age: { bsonType: "int", minimum: 0, maximum: 120 }
      }
    }
  }
})

Adding Validation to an Existing Collection

If the collection already exists, use collMod to attach or change its validator without recreating it.

Modify validation on an existing collection

db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        status: { enum: ["active", "inactive", "banned"] }
      }
    }
  }
})

Controlling Strictness

Two options control how validation behaves: validationLevel decides which documents get checked (strict checks all inserts and updates, moderate only checks documents that were already valid), and validationAction decides what happens on failure (error rejects the write, warn logs a warning but still allows it).

Warn instead of reject

db.runCommand({
  collMod: "users",
  validationLevel: "moderate",
  validationAction: "warn"
})
  • required — array of field names that must be present.
  • properties — per-field type and constraint rules (bsonType, minimum, maximum, pattern, enum).
  • validationLevel — "strict" (default) or "moderate".
  • validationAction — "error" (default, rejects the write) or "warn" (logs only).
SettingValuesEffect
validationLevelstrict / moderateWhether existing invalid documents are re-checked on update
validationActionerror / warnWhether a failing write is rejected or just logged
Note: Validation runs on insertOne, insertMany, updateOne, and similar write operations. It does not retroactively check documents already stored in the collection.
Note: Using validationAction: "warn" is handy while migrating an existing collection to a stricter schema, but remember to switch it back to "error" once your application code is fixed — otherwise invalid data keeps slipping through.

Exercise: MongoDB Validation

By default, does MongoDB enforce a fixed schema on a collection?