$jsonSchema

The $jsonSchema operator validates documents against a JSON Schema definition for data validation and structure enforcement. Discover supported features and limitations.

$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"
exclusiveMinimumnumbersExclusive minimum boundaryAdvanced numeric validation
exclusiveMaximumnumbersExclusive maximum boundaryAdvanced 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
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 JSON Schema keywords are yet to be supported in DocumentDB:

KeywordTypeReason for Non-SupportWorkaround
additionalPropertiesobjectsNot implementedUse explicit properties definitions
allOfall typesLogical operator not supportedUse nested validation
anyOfall typesLogical operator not supportedUse separate queries
dependenciesobjectsComplex dependency validation not supportedHandle in application logic
descriptionN/AMight not appear in error messagesInformational only
enumall typesEnumeration validation not supportedUse $in operator instead
maxPropertiesobjectsProperty count validation not supportedHandle in application logic
minPropertiesobjectsProperty count validation not supportedHandle in application logic
notall typesNegation operator not supportedUse positive validation rules
oneOfall typesLogical operator not supportedUse application-level validation
patternPropertiesobjectsPattern-based property validation not supportedUse explicit property names
titleN/AMetadata field not processedUse description instead

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",
    properties: {
      _id: {
        bsonType: "string"
      },
      name: {
        bsonType: "string",
        minLength: 5,
        maxLength: 100
      },
      location: {
        bsonType: "object",
        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",
    properties: {
      sales: {
        bsonType: "object",
        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 should return this output:

[
  {
    _id: 'new-store-001',
    name: 'Adatum Corporation - Downtown Branch',
    sales: { totalSales: 5000 },
    createdDate: ISODate('2025-06-11T11:11:32.262Z'),
    status: 'new',
    staff: { totalStaff: { fullTime: 0, partTime: 0 } },
    version: 1,
    storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'),
    storeFeatures: 213
  }
]

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: {
        properties: {
          staff: {
            bsonType: "object",
            properties: {
              totalStaff: {
                bsonType: "object",
                properties: {
                  fullTime: {
                    bsonType: "int",
                    minimum: 1
                  }
                }
              }
            }
          }
        }
      }
    },
    // Additional query constraints
    {
      "sales.totalSales": { $gt: 10000 }
    }
  ]
}).limit(1)

This query returns the following result:

[
  {
    _id: 'future-electronics-001',
    address: { city: 'New Tech City' },
    name: 'Boulder Innovations - Future Electronics Hub',
    sales: { totalSales: 25000 },
    establishedDate: ISODate('2025-06-11T11:14:23.147Z'),
    categories: [ 'electronics', 'gadgets', 'smart-home' ],
    promotionEvents: [],
    ratings: { average: 0, count: 0, reviews: [] },
    inventory: {
      lastUpdated: ISODate('2025-06-11T11:14:23.147Z'),
      totalItems: 0,
      lowStockAlerts: []
    },
    storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'),
    storeFeatures: 120
  }
]

Related content