$jsonSchema
Validates documents against a JSON Schema specification to ensure data structure and type conformity.
Syntax
{ $jsonSchema: { bsonType: "object", required: [...], properties: {...} } }
Parameters
bsonType
stringrequiredBSON type specification: "object", "array", "string", "int", "double", "bool", "date", etc.
required
objectArray of field names that must be present in the document
properties
objectObject defining validation rules for specific fields
minimum
numberMinimum value constraint for numeric fields
maximum
numberMaximum value constraint for numeric fields
minLength
numberMinimum string length constraint
maxLength
numberMaximum string length constraint
Examples
Basic structure validation
Validate documents with required name and valid coordinates
Query:
db.stores.find({ $jsonSchema: { bsonType: "object", properties: { name: { bsonType: "string", minLength: 5 }, location: { bsonType: "object", properties: { lat: { bsonType: "double", minimum: -90, maximum: 90 } } } } } })
Output:
Documents that conform to the specified schema structure
Array validation with items schema
Validate sales data with proper array structure and item types
Query:
db.stores.find({ $jsonSchema: { properties: { sales: { bsonType: "object", properties: { salesByCategory: { bsonType: "array", minItems: 1, items: { bsonType: "object", properties: { categoryName: { bsonType: "string" }, totalSales: { bsonType: "int", minimum: 0 } } } } } } } } })
Output:
Documents with valid sales array structure containing proper category objects
Numeric constraints validation
Validate staff numbers are positive integers
Query:
db.stores.find({ $jsonSchema: { properties: { staff: { bsonType: "object", properties: { totalStaff: { bsonType: "object", properties: { fullTime: { bsonType: "int", minimum: 0 }, partTime: { bsonType: "int", minimum: 0 } } } } } } } })
Output:
Documents where staff numbers are non-negative integers
Combined validation with query operators
Use schema validation along with field queries
Query:
db.stores.find({ $and: [{ $jsonSchema: { properties: { name: { bsonType: "string", minLength: 10 } } } }, { "sales.totalSales": { $gt: 10000 } }] })
Output:
Documents that pass schema validation and have sales greater than 10000