0
0
MongodbHow-ToBeginner · 4 min read

How to Use JSON Schema Validation in MongoDB

In MongoDB, you use jsonSchema validation by defining a validator in the createCollection or collMod command. This validator uses a JSON Schema to specify rules for document fields, types, and required properties, ensuring data consistency.
📐

Syntax

To enable JSON Schema validation in MongoDB, you add a validator option with a $jsonSchema object when creating or modifying a collection. The schema defines the expected structure, types, and constraints for documents.

  • validator: The rule that MongoDB uses to check documents.
  • $jsonSchema: The JSON Schema object describing the document format.
  • required: Lists fields that must be present.
  • properties: Defines each field's type and constraints.
mongodb
db.createCollection("myCollection", {
  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"
        }
      }
    }
  }
})
💻

Example

This example creates a collection named users with JSON Schema validation that requires each document to have a username as a string and an email matching a simple pattern. It also enforces that age is an integer greater than or equal to 18.

mongodb
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email", "age"],
      properties: {
        username: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+\\..+$",
          description: "must be a valid email and is required"
        },
        age: {
          bsonType: "int",
          minimum: 18,
          description: "must be an integer >= 18 and is required"
        }
      }
    }
  }
})

// Insert valid document
db.users.insertOne({ username: "alice", email: "alice@example.com", age: 25 })

// Insert invalid document (age < 18)
try {
  db.users.insertOne({ username: "bob", email: "bob@example.com", age: 16 })
} catch(e) {
  print(e.message)
}
Output
Successfully inserted document with username 'alice'. WriteError: Document failed validation: age: Must be greater than or equal to 18
⚠️

Common Pitfalls

Common mistakes when using JSON Schema validation in MongoDB include:

  • Not specifying bsonType correctly, causing unexpected validation failures.
  • Forgetting to include required fields in the required array.
  • Using regex patterns without properly escaping backslashes.
  • Trying to update documents that violate the schema without adjusting the validator.

Always test your schema with sample inserts to catch errors early.

mongodb
/* Wrong: Missing bsonType for 'age' */
db.createCollection("test", {
  validator: {
    $jsonSchema: {
      required: ["age"],
      properties: {
        age: {
          minimum: 0
        }
      }
    }
  }
})

/* Right: Include bsonType to specify data type */
db.createCollection("test", {
  validator: {
    $jsonSchema: {
      required: ["age"],
      properties: {
        age: {
          bsonType: "int",
          minimum: 0
        }
      }
    }
  }
})
📊

Quick Reference

KeywordDescription
validatorDefines the validation rules for the collection.
$jsonSchemaSpecifies the JSON Schema object for validation.
bsonTypeSpecifies the expected BSON data type (e.g., string, int, object).
requiredArray of field names that must be present in documents.
propertiesDefines constraints and types for each field.
patternRegex pattern that string fields must match.
minimumMinimum numeric value allowed for a field.

Key Takeaways

Use the validator option with $jsonSchema to enforce document structure in MongoDB collections.
Always specify bsonType for each field to avoid validation errors.
Include required fields in the required array to ensure they exist in documents.
Test your schema with sample inserts to catch mistakes early.
Use collMod to add or update validation rules on existing collections.