$jsonSchema

Definition

  • $jsonSchema

New in version 3.6.

The $jsonSchema operator matches documents that satisfythe specified JSON Schema.

The $jsonSchema operator expression has the following syntax:

  1. { $jsonSchema: <JSON Schema object> }

Where the JSON Schema object is formatted according to draft 4 ofthe JSON Schema standard.

  1. { <keyword1>: <value1>, ... }

For example:

  1. {
  2. $jsonSchema: {
  3. required: [ "name", "major", "gpa", "address" ],
  4. properties: {
  5. name: {
  6. bsonType: "string",
  7. description: "must be a string and is required"
  8. },
  9. address: {
  10. bsonType: "object",
  11. required: [ "zipcode" ],
  12. properties: {
  13. "street": { bsonType: "string" },
  14. "zipcode": { bsonType: "string" }
  15. }
  16. }
  17. }
  18. }
  19. }

For a list of keywords supported by MongoDB, see Available Keywords.

Note

MongoDB supports draft 4 of JSON Schema, including corespecification andvalidation specification,with some differences. See Extensions andOmissions for details.

For more information about JSON Schema, see theofficial 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 thespecified schema on insert and update operations:

  1. db.createCollection( <collection>, { validator: { $jsonSchema: <schema> } } )
  2. db.runCommand( { collMod: <collection>, validator:{ $jsonSchema: <schema> } } )

Query Conditions

You can use $jsonSchema in query conditions for read and writeoperations to find documents in the collection that satisfy the specifiedschema:

  1. db.collection.find( { $jsonSchema: <schema> } )
  2. db.collection.aggregate( [ { $match: { $jsonSchema: <schema> } } ] )
  3. db.collection.updateMany( { $jsonSchema: <schema> }, <update> )
  4. db.collection.deleteOne( { $jsonSchema: <schema> } )

To find documents in the collection that do not satisfy the specifiedschema, use the $jsonSchema expression in a $norexpression. For example:

  1. db.collection.find( { $nor: [ { $jsonSchema: <schema> } ] } )
  2. db.collection.aggregate( [ { $match: { $nor: [ { $jsonSchema: <schema> } ] } }, ... ] )
  3. db.collection.updateMany( { $nor: [ { $jsonSchema: <schema> } ] }, <update> )
  4. db.collection.deleteOne( { $nor: [ { $jsonSchema: <schema> } ] } )

Examples

Schema Validation

The following db.createCollection() method creates acollection named students and uses the $jsonSchemaoperator to set schema validation rules:

  1. db.createCollection("students", {
  2. validator: {
  3. $jsonSchema: {
  4. bsonType: "object",
  5. required: [ "name", "year", "major", "address" ],
  6. properties: {
  7. name: {
  8. bsonType: "string",
  9. description: "must be a string and is required"
  10. },
  11. year: {
  12. bsonType: "int",
  13. minimum: 2017,
  14. maximum: 3017,
  15. description: "must be an integer in [ 2017, 3017 ] and is required"
  16. },
  17. major: {
  18. enum: [ "Math", "English", "Computer Science", "History", null ],
  19. description: "can only be one of the enum values and is required"
  20. },
  21. gpa: {
  22. bsonType: [ "double" ],
  23. description: "must be a double if the field exists"
  24. },
  25. address: {
  26. bsonType: "object",
  27. required: [ "city" ],
  28. properties: {
  29. street: {
  30. bsonType: "string",
  31. description: "must be a string if the field exists"
  32. },
  33. city: {
  34. bsonType: "string",
  35. "description": "must be a string and is required"
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. })

Given the created validator for the collection, the following insertoperation will fail because gpa is an integer when the validatorrequires a double.

  1. db.students.insert({
  2. name: "Alice",
  3. year: NumberInt(2019),
  4. major: "History",
  5. gpa: NumberInt(3),
  6. address: {
  7. city: "NYC",
  8. street: "33rd Street"
  9. }
  10. })

The operation returns the following error:

  1. WriteResult({
  2. "nInserted" : 0,
  3. "writeError" : {
  4. "code" : 121,
  5. "errmsg" : "Document failed validation"
  6. }
  7. })

After changing the gpa to a double, the insert succeeds:

  1. db.students.insert({
  2. name: "Alice",
  3. year: NumberInt(2019),
  4. major: "History",
  5. gpa: 3.0,
  6. address: {
  7. city: "NYC",
  8. street: "33rd Street"
  9. }
  10. })

The operation returns the following:

  1. WriteResult({ "nInserted" : 1 })

Query Conditions

You can use $jsonSchema in query conditions for read and writeoperations to find documents in the collection that satisfy the specifiedschema.

For example, create a sample collection inventory with thefollowing documents:

  1. db.inventory.insertMany([
  2. { item: "journal", qty: NumberInt(25), size: { h: 14, w: 21, uom: "cm" }, instock: true },
  3. { item: "notebook", qty: NumberInt(50), size: { h: 8.5, w: 11, uom: "in" }, instock: true },
  4. { item: "paper", qty: NumberInt(100), size: { h: 8.5, w: 11, uom: "in" }, instock: 1 },
  5. { item: "planner", qty: NumberInt(75), size: { h: 22.85, w: 30, uom: "cm" }, instock: 1 },
  6. { item: "postcard", qty: NumberInt(45), size: { h: 10, w: 15.25, uom: "cm" }, instock: true },
  7. { item: "apple", qty: NumberInt(45), status: "A", instock: true },
  8. { item: "pears", qty: NumberInt(50), status: "A", instock: true }
  9. ])

Next, define the following sample schema object:

  1. let myschema = {
  2. required: [ "item", "qty", "instock" ],
  3. properties: {
  4. item: { bsonType: "string" },
  5. qty: { bsonType: "int" },
  6. size: {
  7. bsonType: "object",
  8. required: [ "uom" ],
  9. properties: {
  10. uom: { bsonType: "string" },
  11. h: { bsonType: "double" },
  12. w: { bsonType: "double" }
  13. }
  14. },
  15. instock: { bsonType: "bool" }
  16. }
  17. }

You can use $jsonSchema to find all documents in thecollection that satisfy the schema:

  1. db.inventory.find( { $jsonSchema: myschema } )
  2. db.inventory.aggregate( [ { $match: { $jsonSchema: myschema } } ] )

You can use $jsonSchema with the $nor to find alldocuments that do not satisfy the schema:

  1. db.inventory.find( { $nor: [ { $jsonSchema: myschema } ] } )

Or, you can update all documents that do not satisfy the schema:

  1. db.inventory.updateMany( { $nor: [ { $jsonSchema: myschema } ] }, { $set: { isValid: false } } )

Or, you can delete all documents that do not satisfy the schema:

  1. db.inventory.deleteMany( { $nor: [ { $jsonSchema: myschema } ] } )

JSON Schema

MongoDB supports draft 4 of JSON Schema, includingcore specificationand validation specification,with some differences. See Extensions and Omissions for details.

For more information about JSON Schema, see theofficial website.

Available Keywords

Note

MongoDB implements a subset of keywords available in JSON Schema.For a complete list of omissions, see Omissions.

KeywordTypeDefinitionBehavior
bsonTypeall typesstring alias or array of string aliasesAccepts same string aliasesused for the $type operator
enumall typesarray of valuesEnumerates all possible values of the field
typeall typesstring or array of unique stringsEnumerates the possible JSON types of the field. Available types are“object”, “array”, “number”, “boolean”, “string”, and “null”.MongoDB’s implementation of the JSON Schema does not support the“integer” type. Use the bsonType keyword and the“int” or “long” types instead.
allOfall typesarray of JSON Schema objectsField must match all specified schemas
anyOfall typesarray of JSON Schema objectsField must match at least one of the specified schemas
oneOfall typesarray of JSON Schema objectsField must match exactly one of the specified schemas
notall typesa JSON Schema objectField must not match the schema
multipleOfnumbersnumberField must be a multiple of this value
maximumnumbersnumberIndicates the maximum value of the field
exclusiveMaximumnumbersbooleanIf true and field is a number, maximum is an exclusive maximum.Otherwise, it is an inclusive maximum.
minimumnumbersnumberIndicates the minimum value of the field
exclusiveMinimumnumbersbooleanIf true, minimum is an exclusive minimum. Otherwise, it is aninclusive minimum.
maxLengthstringsintegerIndicates the maximum length of the field
minLengthstringsintegerIndicates the minimum length of the field
patternstringsstring containing a regexField must match the regular expression
maxPropertiesobjectsintegerIndicates the field’s maximum number of properties
minPropertiesobjectsintegerIndicates the field’s minimum number of properties
requiredobjectsarray of unique stringsObject’s property set must contain all the specified elements in thearray
additionalPropertiesobjectsboolean or objectIf true, additional fields are allowed. If false, they are not.If a valid JSON Schema object is specified, additional fields mustvalidate against the schema.Defaults to true.
propertiesobjectsobjectA valid JSON Schema where each value is also a valid JSON Schema object
patternPropertiesobjectsobjectIn addition to properties requirements, each property name of thisobject must be a valid regular expression
dependenciesobjectsobjectDescribes field or schema dependencies
additionalItemsarraysboolean or objectIf an object, must be a valid JSON Schema
itemsarraysobject or arrayMust be either a valid JSON Schema, or an array of valid JSON Schemas
maxItemsarraysintegerIndicates the maximum length of array
minItemsarraysintegerIndicates the minimum length of array
uniqueItemsarraysbooleanIf true, each item in the array must be unique. Otherwise, no uniquenessconstraint is enforced.
titleN/AstringA descriptive title string with no effect.
descriptionN/AstringA string that describes the schema and has no effect.

Extensions

MongoDB’s implementation of JSON Schema includes the addition of the bsonTypekeyword, which allows you to use all BSON types in the$jsonSchema operator. bsonType accepts the same string aliases usedfor the $type operator.

Omissions

The following are not supported in MongoDB’s implementation of JSON Schema:

  • Hypertext definitionsin draft 4 of the JSON Schema spec.
  • The keywords:
    • $ref
    • $schema
    • default
    • definitions
    • format
    • id
  • The integer type. You must use the BSON type int or longwith the bsonType keyword.
  • Hypermedia and linking properties of JSON Schema, including the use ofJSON References and JSON Pointers.
  • Unknown keywords.