$jsonSchema

Validates documents against a JSON Schema specification to ensure data structure and type conformity.

Syntax

{ $jsonSchema: { bsonType: "object", required: [...], properties: {...} } }

Parameters

bsonTypestringrequired

BSON type specification: "object", "array", "string", "int", "double", "bool", "date", etc.

requiredobject

Array of field names that must be present in the document

propertiesobject

Object defining validation rules for specific fields

minimumnumber

Minimum value constraint for numeric fields

maximumnumber

Maximum value constraint for numeric fields

minLengthnumber

Minimum string length constraint

maxLengthnumber

Maximum 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

Related