NewDocumentDB 1.0 is here. See what's new
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

ParameterDescription
bsonTypeSpecifies the Binary JSON (BSON) types that the field must match. Accepts string aliases used by the $type operator.
propertiesObject defining validation rules for specific fields.
minimum/maximumNumeric constraints for number fields.
minLength/maxLengthString length constraints.
minItems/maxItemsArray length constraints.
patternRegular expression pattern for string validation.
itemsSchema validation for array elements.
uniqueItemsBoolean indicating if array items must be unique.

Supported Keywords

DocumentDB supports the following JSON Schema keywords:

KeywordTypeDescriptionUsage
additionalItemsarraysSchema for extra array itemsExtended array validation
bsonTypeall typesMongoDB extension - accepts BSON type aliases"string", "int", "double", "object", "array", "bool", "date"
descriptionN/AInformational text; must be a stringDocumentation only
enumall typesValue must equal one of the listed valuesRestrict a field to fixed values
exclusiveMinimumnumbersBoolean; makes minimum exclusive (requires minimum)Advanced numeric validation
exclusiveMaximumnumbersBoolean; makes maximum exclusive (requires maximum)Advanced numeric validation
itemsarraysSchema for array elementsArray element validation
minimumnumbersMinimum value constraintNumeric validation
maximumnumbersMaximum value constraintNumeric validation
minItemsarraysMinimum array lengthArray size validation
maxItemsarraysMaximum array lengthArray size validation
multipleOfnumbersValue must be multiple of specified numberMathematical constraints
minLengthstringsMinimum string lengthString validation
maxLengthstringsMaximum string lengthString validation
oneOfall typesValue must match exactly one of the listed subschemasAlternative structures
patternstringsRegular expression pattern matchingString format validation
propertiesobjectsDefine validation rules for object fieldsSchema definition for nested objects
requiredobjectsArray of required field namesEnforce mandatory fields
typeall typesStandard JSON Schema types"object", "array", "number", "boolean", "string", "null"
uniqueItemsarraysEnforce unique array elementsData integrity

Unsupported Keywords

These keywords are rejected with The '<keyword>' keyword in $jsonSchema is not supported at this time:

KeywordTypeWorkaround
$refN/AInline the referenced schema
$schemaN/AOmit it
defaultN/ASet defaults in application logic
definitionsN/AInline the subschemas
formatstringsUse pattern
idN/AOmit 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 }
  }
]