MongoDb - MongoDB Validation

MongoDB is schema-flexible, meaning by default collections don’t enforce a strict schema. But starting from MongoDB 3.2, you can enforce document validation rules to control what data gets inserted or updated.


1. What is Validation in MongoDB?

  • Validation lets you define rules that documents must follow before being written to the collection.

  • Helps maintain data consistency while still keeping flexibility.

  • Validation rules are defined when creating or modifying a collection.


2. Create a Collection with Validation

You can specify a validator when creating a collection:

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      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"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "must be a valid email"
        }
      }
    }
  }
})

3. Insert Examples

Valid insert:

db.users.insertOne({ name: "Alice", age: 25, email: "[email protected]" })

 Invalid insert (fails validation):

db.users.insertOne({ name: "Bob", age: 15 })  // age < 18

4. Validation Action Modes

You can control what happens if a document fails validation:

  • validationAction: "error" (default) → reject invalid documents.

  • validationAction: "warn" → allow insert/update but log a warning.

Example:

db.runCommand({
  collMod: "users",
  validator: { age: { $gte: 18 } },
  validationAction: "warn"
})

5. Validation Level

Controls which operations validation applies to:

  • strict (default) → validate all inserts and updates.

  • moderate → validate only documents being inserted or modified (existing docs remain).

Example:

db.runCommand({
  collMod: "users",
  validator: { age: { $gte: 18 } },
  validationLevel: "moderate"
})

6. Update Existing Collection with Validation

You can use collMod to modify validation rules on an existing collection:

db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"]
    }
  }
})

7. Simple Validator without JSON Schema

You can also use MongoDB query expressions:

db.createCollection("products", {
  validator: { price: { $gte: 0 } }
})

This ensures price is always ≥ 0.


Summary

  • MongoDB is schema-flexible, but you can enforce validation rules.

  • Use validator with $jsonSchema for detailed schema enforcement.

  • Modes:

    • validationAction: "error" or "warn"

    • validationLevel: "strict" or "moderate"

  • Modify rules later with collMod.