MongoDB - Getting StartedMongoDB - Getting Started1

Defining Custom Validation Rules in MongoDB



Defining Custom Validation Rules in MongoDB

In MongoDB, even though schemas are flexible, you can still define validation rules to ensure data quality and consistency using JSON Schema validation.

This is useful when you want to allow flexibility, but still enforce structure—like requiring a field to be a string, or restricting values to a specific set.

Why Use Validation Rules?

MongoDB’s dynamic schema is powerful, but with great power comes the possibility of bad data. Validation allows you to:

How Does MongoDB Schema Validation Work?

MongoDB lets you define validation rules using JSON Schema when creating or updating a collection.

Example 1: Basic Required Fields and Type Check

Let’s create a students collection where:


    db.createCollection("students", {
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["name", "age"],
          properties: {
            name: {
              bsonType: "string",
              description: "must be a string and is required"
            },
            age: {
              bsonType: "int",
              minimum: 0,
              description: "must be an integer ≥ 0 and is required"
            }
          }
        }
      }
    });
    

Output:

    { ok: 1 }
    

Explanation: The schema requires both name and age. The age must be an integer and not negative. Any document violating this will be rejected.

Test Insert


    db.students.insertOne({ name: "Asha", age: 20 });
    

Output:

    {
      acknowledged: true,
      insertedId: ObjectId("...")
    }
    

Try Invalid Insert


    db.students.insertOne({ name: "Ravi", age: "twenty" });
    

Output:

    WriteError: Document failed validation
    

Question:

Why does MongoDB reject the second document?

Answer: Because the age is a string ("twenty") and not an integer as required by the validation rule.

Example 2: Using Enums to Restrict Values

Let’s now allow only specific values for a status field (e.g., “active”, “inactive”, “pending”).


    db.createCollection("accounts", {
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["username", "status"],
          properties: {
            username: {
              bsonType: "string",
              description: "must be a string and is required"
            },
            status: {
              enum: ["active", "inactive", "pending"],
              description: "can only be one of the enum values"
            }
          }
        }
      }
    });
    

Try a Valid Insert:


    db.accounts.insertOne({ username: "john_doe", status: "active" });
    

Output:

    {
      acknowledged: true,
      insertedId: ObjectId("...")
    }
    

Try an Invalid Insert:


    db.accounts.insertOne({ username: "jane_doe", status: "banned" });
    

Output:

    WriteError: Document failed validation
    

Example 3: Allowing Optional Fields

Let’s say you want to allow an optional email field, but if it exists, it must be a string:


    db.createCollection("employees", {
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["name"],
          properties: {
            name: {
              bsonType: "string"
            },
            email: {
              bsonType: "string"
            }
          }
        }
      }
    });
    

Explanation: Here, email is not required but still validated if provided. This is useful for optional fields.

How to Check Collection Validator


    db.getCollectionInfos({ name: "students" })
    

How to Update Validation Rules on an Existing Collection


    db.runCommand({
      collMod: "students",
      validator: {
        $jsonSchema: {
          bsonType: "object",
          required: ["name", "age"],
          properties: {
            name: { bsonType: "string" },
            age: { bsonType: "int", minimum: 0 }
          }
        }
      }
    });
    

Summary

Validation rules in MongoDB allow you to enforce a structure within your flexible schema. You can require fields, set type restrictions, limit values, and even define nested document structure. This helps ensure the data inserted into collections is meaningful and consistent.

Now that you know how to define custom validation rules, you’re ready to build MongoDB collections that are both powerful and safe from invalid data.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M