MongoDB $jsonSchema Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Validation

What You’ll Learn

The $jsonSchema operator validates documents against a JSON Schema rules object. Use it in $match to find well-formed records, or attach it to a collection to enforce data integrity on inserts and updates.

01

Schema Rules

Define valid shapes.

02

bsonType

MongoDB type checks.

03

required

Mandatory fields.

04

$match Filter

Find valid documents.

05

Collection Validator

Enforce on write.

06

properties

Per-field rules.

Definition and Usage

In MongoDB, the $jsonSchema operator checks whether a document satisfies a set of validation rules written in JSON Schema style. You can require certain fields, restrict types with bsonType, set minimum and maximum values, allow only specific enum values, and validate nested objects.

There are two main use cases. In queries and $match stages, $jsonSchema filters documents that already match your rules — useful for data quality audits. As a collection validator, it enforces rules on new writes, preventing malformed data from entering the database.

💡
Beginner Tip

MongoDB extends standard JSON Schema with bsonType for BSON-specific types like "date", "objectId", and "int". Use bsonType instead of generic type when validating MongoDB documents.

📝 Syntax

The $jsonSchema operator wraps a JSON Schema rules object:

mongosh
{
  $jsonSchema: {
    bsonType: "object",
    required: [ "field1", "field2" ],
    properties: {
      field1: { bsonType: "string" },
      field2: { bsonType: "int", minimum: 0 }
    },
    additionalProperties: false
  }
}

Common Schema Keywords

  • bsonType — BSON type: "object", "string", "int", "double", "bool", "date", "array", "objectId".
  • required — array of field names that must be present.
  • properties — per-field validation rules for known keys.
  • minimum / maximum — numeric range constraints.
  • enum — allowed values for a field.
  • minLength / maxLength — string length limits.
  • additionalProperties — whether extra fields not listed in properties are allowed.

💡 $match Filter vs Collection Validator

Same schema object, different purpose:

$match / find() → returns documents that already match the schema (audit / filter)
createCollection validator → blocks or warns on new writes that violate the schema (enforce)
validationAction"error" rejects invalid docs; "warn" logs but allows

⚡ Quick Reference

QuestionAnswer
Operator typeQuery operator (validation)
Syntax{ $jsonSchema: { ...rules } }
In $matchReturns documents matching the schema
On collectionEnforces rules on insert/update
Common stages$match, find(), collection validator
Required fields
{
  $jsonSchema: {
    required: ["email"]
  }
}

Must have email

Type check
{
  $jsonSchema: {
    properties: {
      age: { bsonType: "int" }
    }
  }
}

age must be int

Enum values
{
  $jsonSchema: {
    properties: {
      status: {
        enum: ["active", "pending"]
      }
    }
  }
}

Allowed statuses

Collection
db.createCollection(
  "users",
  { validator: {
    $jsonSchema: { ... }
  }}
)

Enforce on write

Examples Gallery

Walk through a users collection, filter valid documents with $match, and set up a collection validator to enforce rules on new writes.

📚 Find Valid Documents

Use $jsonSchema in $match to return only documents that meet your schema rules.

Sample Input Documents

A users collection with mixed data quality:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "email": "alice@example.com", "age": 28, "status": "active" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "age": "thirty", "status": "active" },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "email": "charlie@example.com", "age": 35, "status": "unknown" }
]

Bob is missing email and has a string age. Charlie has an invalid status value.

Example 1 — $jsonSchema in a $match Stage

Find users with required fields, correct types, and allowed status values:

mongosh
db.users.aggregate([
  {
    $match: {
      $jsonSchema: {
        bsonType: "object",
        required: [ "name", "email", "age", "status" ],
        properties: {
          name:   { bsonType: "string" },
          email:  { bsonType: "string" },
          age:    { bsonType: "int", minimum: 0 },
          status: { enum: [ "active", "pending", "archived" ] }
        }
      }
    }
  }
])

How It Works

  • required ensures all four fields exist on the document.
  • bsonType checks that age is an integer, not a string like "thirty".
  • enum restricts status to the three allowed values.

📈 Practical Patterns

Validate nested objects, enforce schemas on collections, and audit data quality.

Example 2 — Validate a Nested Object

Require an address object with city and country strings:

mongosh
db.users.aggregate([
  {
    $match: {
      $jsonSchema: {
        bsonType: "object",
        required: [ "name", "address" ],
        properties: {
          name: { bsonType: "string" },
          address: {
            bsonType: "object",
            required: [ "city", "country" ],
            properties: {
              city:    { bsonType: "string" },
              country: { bsonType: "string", minLength: 2 }
            }
          }
        }
      }
    }
  }
])

How It Works

Nested properties apply rules to sub-documents. Each level can have its own required, bsonType, and length constraints.

Example 3 — find() with $jsonSchema

The same schema works outside aggregation in a plain find() query:

mongosh
db.users.find({
  $jsonSchema: {
    bsonType: "object",
    required: [ "email" ],
    properties: {
      email: {
        bsonType: "string",
        pattern: "^.+@.+\\..+$"
      }
    }
  }
})

How It Works

The pattern keyword applies a regular expression to string fields. Here it checks for a basic email shape with @ and a domain dot.

Example 4 — Collection Validator on Create

Enforce schema rules when documents are inserted or updated:

mongosh
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "name", "price", "status" ],
      properties: {
        name:   { bsonType: "string", minLength: 1 },
        price:  { bsonType: [ "int", "double" ], minimum: 0 },
        status: { enum: [ "active", "draft", "archived" ] }
      },
      additionalProperties: false
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

How It Works

validationLevel: "strict" validates all inserts and updates. validationAction: "error" rejects invalid writes. additionalProperties: false blocks fields not listed in properties.

Bonus — Add a Validator to an Existing Collection

Use collMod to attach or update validation rules later:

mongosh
db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "email" ],
      properties: {
        email: { bsonType: "string" }
      }
    }
  },
  validationLevel: "moderate",
  validationAction: "warn"
})

How It Works

validationLevel: "moderate" validates updates only if the document already passed validation (or is new). validationAction: "warn" logs violations without blocking writes — useful when rolling out schema rules on legacy data.

🚀 Use Cases

  • Data quality audits — use $match with $jsonSchema to find documents that fail your rules.
  • Collection enforcement — prevent invalid inserts and updates at the database level.
  • API contract alignment — mirror your application’s expected document shape in MongoDB validators.
  • Migration safety — start with validationAction: "warn", fix data, then switch to "error".

🧠 How $jsonSchema Works

1

MongoDB loads the schema rules

The $jsonSchema object defines required fields, types, ranges, enums, and nested constraints.

Rules
2

Each document is validated

In $match, MongoDB checks existing documents. As a validator, it checks documents on insert and update.

Validate
3

Pass or fail is applied

Matching documents are returned in queries. Invalid writes are rejected (error) or logged (warn) based on settings.

Result
=

Cleaner, predictable data

You get documents that follow your schema — whether filtering existing data or blocking bad writes.

Conclusion

The $jsonSchema operator brings structured validation to MongoDB without requiring a rigid relational schema. Use it in $match to audit existing data, and attach it as a collection validator to protect your database from malformed writes going forward.

For beginners, start with required and bsonType in properties, then add enum, ranges, and nested rules as your needs grow. Roll out collection validators with validationAction: "warn" first if you have legacy data.

💡 Best Practices

✅ Do

  • Use bsonType for MongoDB-specific type checks
  • Start validators with validationAction: "warn" on existing collections
  • Keep schemas focused — validate critical fields first
  • Use $match + $jsonSchema to audit before enforcing
  • Document your schema rules for your team

❌ Don’t

  • Use $jsonSchema inside $project (it is a query operator)
  • Enable validationAction: "error" before cleaning legacy data
  • Confuse bsonType: "int" with string numbers like "42"
  • Over-restrict with additionalProperties: false too early
  • Assume validators replace application-level validation entirely

Key Takeaways

Knowledge Unlocked

Five things to remember about $jsonSchema

Use these points when validating MongoDB documents.

5
Core concepts
📝 02

bsonType

MongoDB type keyword.

Syntax
🛠 03

Two Modes

$match vs validator.

Usage
📋 04

required + enum

Common constraints.

Pattern
05

warn First

Then switch to error.

Rollout

❓ Frequently Asked Questions

$jsonSchema validates documents against a JSON Schema rules object. In $match it returns documents that satisfy the schema. On a collection it can reject or warn on inserts and updates that violate the rules.
Query form: { $jsonSchema: { bsonType: "object", required: [...], properties: { ... } } }. Collection validator: pass the same $jsonSchema object to the validator option in createCollection or collMod.
MongoDB uses bsonType for BSON-specific types like "int", "double", "date", "objectId", and "bool". Standard JSON Schema type keywords also work for some cases, but bsonType is preferred in MongoDB validators.
Use it in find() filters, $match aggregation stages, and as a collection validator via createCollection or collMod. It is a query operator, not an aggregation expression like $project.
validationLevel controls when validation runs ("off", "strict", or "moderate"). validationAction sets whether invalid documents are rejected ("error") or allowed with a warning ("warn"). These apply to collection validators, not $match queries.

Continue the Operator Series

Move on to $let for local variables in expressions, or review $exists for field presence checks.

Next: $let →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful