$jsonSchema
On this page
Definition
-
$jsonSchema
-
New in version 3.6.
The
$jsonSchema
operator matches documents that satisfy the specified JSON Schema.The
$jsonSchema
operator expression has the following syntax:Where the JSON Schema object is formatted according to draft 4 of the JSON Schema standard .
For example:
For a list of keywords supported by MongoDB, see Available Keywords.
Note
MongoDB supports draft 4 of JSON Schema, including core specification and validation specification , with some differences. See Extensions and Omissions for details.
For more information about JSON Schema, see the official website .
Behavior
Feature Compatibility
The featureCompatibilityVersion must be set to "3.6"
or higher in order to use $jsonSchema
.
Document Validator
You can use $jsonSchema
in a document validator to enforce the specified schema on insert and update operations:
Query Conditions
You can use $jsonSchema
in query conditions for read and write operations to find documents in the collection that satisfy the specified schema:
To find documents in the collection that do not satisfy the specified schema, use the $jsonSchema
expression in a $nor
expression. For example:
Examples
Schema Validation
The following db.createCollection()
method creates a collection named students
and uses the $jsonSchema
operator to set schema validation rules:
Given the created validator
for the collection, the following insert operation will fail because gpa
is an integer when the validator
requires a double
.
The operation returns the following error:
After changing the gpa
to a double, the insert succeeds:
The operation returns the following:
Query Conditions
You can use $jsonSchema
in query conditions for read and write operations to find documents in the collection that satisfy the specified schema.
For example, create a sample collection inventory
with the following documents: