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.
Fundamentals
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, $jsonSchemafilters 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.
Foundation
📝 Syntax
The $jsonSchema operator wraps a JSON Schema rules object:
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "email": "alice@example.com", "age": 28, "status": "active" }
// Bob excluded: missing email, age is string
// Charlie excluded: status "unknown" not in enum
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:
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:
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.
Applications
🚀 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.
Wrap Up
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.
Use these points when validating MongoDB documents.
5
Core concepts
🔒01
Schema Validation
Rules-based checks.
Purpose
📝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.