MQL reference navigation
$jsonSchema
The $jsonSchema operator is used to validate documents against a JSON Schema specification. It ensures that documents conform to a predefined structure, data types, and validation rules.
Syntax
The syntax for the $jsonSchema operator is as follows:
db.createCollection("collectionName", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["field1", "field2"],
properties: {
field1: {
bsonType: "string",
description: "Description of field1 requirements"
},
field2: {
bsonType: "int",
minimum: 0,
description: "Description of field2 requirements"
}
}
}
},
validationLevel: "strict", // Optional: "strict" or "moderate"
validationAction: "error" // Optional: "error" or "warn"
})Parameters
| Parameter | Description |
|---|---|
bsonType | Specifies the Binary JSON (BSON) types that the field must match. Accepts string aliases used by the $type operator. |
properties | Object defining validation rules for specific fields. |
minimum/maximum | Numeric constraints for number fields. |
minLength/maxLength | String length constraints. |
minItems/maxItems | Array length constraints. |
pattern | Regular expression pattern for string validation. |
items | Schema validation for array elements. |
uniqueItems | Boolean indicating if array items must be unique. |
Supported Keywords
DocumentDB supports the following JSON Schema keywords:
| Keyword | Type | Description | Usage |
|---|---|---|---|
additionalItems | arrays | Schema for extra array items | Extended array validation |
bsonType | all types | MongoDB extension - accepts BSON type aliases | "string", "int", "double", "object", "array", "bool", "date" |
description | N/A | Informational text; must be a string | Documentation only |
enum | all types | Value must equal one of the listed values | Restrict a field to fixed values |
exclusiveMinimum | numbers | Boolean; makes minimum exclusive (requires minimum) | Advanced numeric validation |
exclusiveMaximum | numbers | Boolean; makes maximum exclusive (requires maximum) | Advanced numeric validation |
items | arrays | Schema for array elements | Array element validation |
minimum | numbers | Minimum value constraint | Numeric validation |
maximum | numbers | Maximum value constraint | Numeric validation |
minItems | arrays | Minimum array length | Array size validation |
maxItems | arrays | Maximum array length | Array size validation |
multipleOf | numbers | Value must be multiple of specified number | Mathematical constraints |
minLength | strings | Minimum string length | String validation |
maxLength | strings | Maximum string length | String validation |
oneOf | all types | Value must match exactly one of the listed subschemas | Alternative structures |
pattern | strings | Regular expression pattern matching | String format validation |
properties | objects | Define validation rules for object fields | Schema definition for nested objects |
required | objects | Array of required field names | Enforce mandatory fields |
type | all types | Standard JSON Schema types | "object", "array", "number", "boolean", "string", "null" |
uniqueItems | arrays | Enforce unique array elements | Data integrity |
Unsupported Keywords
These keywords are rejected with The '<keyword>' keyword in $jsonSchema is not supported at this time:
| Keyword | Type | Workaround |
|---|---|---|
$ref | N/A | Inline the referenced schema |
$schema | N/A | Omit it |
default | N/A | Set defaults in application logic |
definitions | N/A | Inline the subschemas |
format | strings | Use pattern |
id | N/A | Omit it |
encrypt and encryptMetadata are accepted so that client-side field-level encryption schemas parse; DocumentDB doesn't encrypt anything.
Any other keyword, including additionalProperties, allOf, anyOf, dependencies, maxProperties, minProperties, not, patternProperties, and title, is rejected with Unknown $jsonSchema keyword: <keyword>.
Examples
Let's explore practical examples using the stores dataset:
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"location": {
"lat": 60.7954,
"lon": -142.0012
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
}
},
"sales": {
"totalSales": 37701,
"salesByCategory": [
{
"categoryName": "Mattress Toppers",
"totalSales": 37701
}
]
}
}Example 1: Basic Structure Validation
This query retrieves all stores with names between 5 and 100 characters long, and that geographic coordinates fall within valid ranges: latitude between -90 and 90, and longitude between -180 and 180.
db.stores.find({
$jsonSchema: {
bsonType: "object",
required: ["name", "location"],
properties: {
_id: {
bsonType: "string"
},
name: {
bsonType: "string",
minLength: 5,
maxLength: 100
},
location: {
bsonType: "object",
required: ["lat", "lon"],
properties: {
lat: {
bsonType: "double",
minimum: -90,
maximum: 90
},
lon: {
bsonType: "double",
minimum: -180,
maximum: 180
}
}
}
}
}
}).limit(1)
Example 2: Sales Validation with Array Items
This query retrieves all store documents where the sales field is a valid object containing a non-negative totalSales value and a salesByCategory array with at least one item.
db.stores.find({
$jsonSchema: {
bsonType: "object",
required: ["sales"],
properties: {
sales: {
bsonType: "object",
required: ["totalSales", "salesByCategory"],
properties: {
totalSales: {
bsonType: "int",
minimum: 0
},
salesByCategory: {
bsonType: "array",
minItems: 1,
items: {
bsonType: "object",
properties: {
categoryName: {
bsonType: "string",
minLength: 1
},
totalSales: {
bsonType: "int",
minimum: 0
}
}
}
}
}
}
}
}
}).limit(1)
This query matches one store in the sample data. Its name and sales fields are:
[
{
_id: 'f2a8c190-28e4-4e14-9d8b-0256e53dca66',
name: 'Fabrikam, Inc. | Car Accessory Outlet - West Adele',
sales: {
salesByCategory: [
{ categoryName: 'Phone Mounts', totalSales: 12000 },
{ categoryName: 'Dash Cameras', totalSales: 22300 }
],
peakSalesRecord: 100000,
revenue: 50000,
totalSales: 50000
}
}
]Example 3: Combining with Query Operators
This query retrieves all store documents where the staff field is a valid object that includes a totalStaff subobject with at least one full-time staff member (fullTime ≥ 1) and sales.totalSales greater than 10,000.
db.stores.find({
$and: [
{
$jsonSchema: {
required: ["staff"],
properties: {
staff: {
bsonType: "object",
required: ["totalStaff"],
properties: {
totalStaff: {
bsonType: "object",
required: ["fullTime"],
properties: {
fullTime: {
bsonType: "int",
minimum: 1
}
}
}
}
}
}
}
},
// Additional query constraints
{
"sales.totalSales": { $gt: 10000 }
}
]
}).limit(1)This query matches one store in the sample data. Its name, staff and sales.totalSales fields are:
[
{
_id: 'f2a8c190-28e4-4e14-9d8b-0256e53dca66',
name: 'Fabrikam, Inc. | Car Accessory Outlet - West Adele',
staff: {
maxStaffCapacity: 25,
employeeCount: { fullTime: 10, partTime: 2 },
totalStaff: { fullTime: 10, partTime: 2 }
},
sales: { totalSales: 50000 }
}
]