$jsonSchema is a MongoDB query operator that checks whether a document matches a JSON Schema rules object. Use it in $match / find() to filter good documents, or attach the same rules as a collection validator to protect inserts and updates.
Remember
$jsonSchema = document must match these rules
{ $jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
name: { bsonType: "string" },
age: { bsonType: "int", minimum: 0 }
}
}
}
find / $match → filter matching docs
validator → reject or warn on bad writes
prefer bsonType over type
document = { name: "Asha", age: 14 }
checks:
required name ✓
required age ✓
name is string ✓
age is int ≥ 0 ✓
match → YES (kept by find / $match)
Trace
Worked Walkthrough — Student Shape
A class roster should always store a student name (string) and age (non-negative int). One document is valid; another is missing age.
Calculation
Schema:
required: ["name", "age"]
name → string
age → int, minimum 0
Doc A: { name: "Asha", age: 14 }
name present + string ✓
age present + int ≥ 0 ✓
→ MATCH
Doc B: { name: "Ravi" }
age missing ✗
→ NO MATCH
find({ $jsonSchema: schema }) → only Doc A
Code
MongoDB Examples
We use one small students collection. First insert sample docs, then filter with $jsonSchema, then show a collection validator. Run these in mongosh.
Example 1 — Sample Data
Imagine two student records. Asha has a complete shape; Ravi is missing age. We save them in a collection named students.
// First insert — accepted
{ acknowledged: true, insertedId: ObjectId("...") }
// Second insert — rejected
MongoServerError: Document failed validation
How It Works
Attach the schema.createCollection stores the same $jsonSchema as a validator.
Valid write passes. Asha has name and age, so insert succeeds.
Invalid write fails. With validationAction: "error", Ravi’s missing age is rejected.
Edge Cases & Pitfalls
Check these before shipping a validator to production.
types
Shell numbers are doubles
In mongosh, age: 14 is a double. For bsonType: "int", insert with NumberInt(14)—or allow both: bsonType: ["int", "double"].
modes
Filter ≠ enforce
find / $match only hide bad docs. Collection validators stop bad writes. Same schema, different job.
rollout
Warn before error
Start with validationAction: "warn" on existing collections, fix bad data, then switch to "error".
extra
additionalProperties
By default extra fields are allowed. Set additionalProperties: false only when you want a strict closed shape.
Analysis
Performance Notes
Approach
Cost
Best for
find + $jsonSchema
Per-doc schema check
Audits / one-off cleanups
Collection validator
Check on each write
Ongoing data quality
Simple $type / $exists
Cheaper single-field
One-field filters
Keep schemas lean—only the fields you truly need. For hot paths, prefer $type or $exists when a full schema is overkill.
Remember
Key Takeaways
Role: match a document against JSON Schema rules.
Two modes: filter with find/$match, or enforce with a validator.
Types: prefer bsonType for MongoDB fields.
Sample: required name string + age int ≥ 0.
One line:$jsonSchema answers “does this document match my rules?”—for queries or for write protection.
Frequently Asked Questions
$jsonSchema checks whether a document matches a JSON Schema rules object. In find() or $match it returns documents that already satisfy the rules. As a collection validator it can reject or warn on inserts and updates that break the rules.
Use { $jsonSchema: { bsonType: "object", required: [...], properties: { ... } } }. The same schema object works in find/$match and in createCollection or collMod validators.
Prefer bsonType in MongoDB. It covers BSON types such as int, double, date, objectId, and bool. Remember: mongosh treats bare numbers as doubles, so use NumberInt() when your schema requires bsonType "int".
Use it in find() filters, $match aggregation stages, and as a collection validator via createCollection or collMod. It is a query/validation operator, not an aggregation expression like $addFields.
These apply only to collection validators. validationLevel is off, strict, or moderate. validationAction is error (reject invalid writes) or warn (allow but log). They do not apply to find/$match filters.
No. For one-field checks, $type and $exists stay simpler. Use $jsonSchema when you need a full document shape—required fields, nested rules, enums, and ranges together.