</>
Skip to content
MongoDB lessons (30/38)

MongoDB — Validation

Basic Validation

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

Validation Levels

LevelDescription
strictReject invalid docs
moderateAllow updates to existing
db.runCommand({
  collMod: "users",
  validationLevel: "moderate"
})

Validation Actions

ActionDescription
errorReject invalid
warnLog warning
db.runCommand({
  collMod: "users",
  validationAction: "warn"
})

Add Validation

db.runCommand({
  collMod: "users",
  validator: { ... }
})

Mini Practice

  1. Add validation rules
  2. Test validation
  3. Change validation level
  4. Remove validation

Up Next

Continue with Security — MongoDB security.

Related Topics

Frequently Asked Questions about Validation

What is Validation in MongoDB?

Validation is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Validation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.

Why is Validation important in MongoDB?

Validation is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.