We will add support for JSON Schema via a new $jsonSchema operator in the match language. The following syntax can be used to create a collection with a JSON Schema specification as <schema>:
db.createCollection("myCollectionName", {validator: {$jsonSchema: <schema>}});
For example, the following creates a collection called stringsOnly in which the str field, if present, must be of type "string":
> db.stringsOnly.drop() false > db.createCollection("stringsOnly", {validator: {$jsonSchema: {properties: {str: {type: "string"}}}}}); { "ok" : 1 } > db.stringsOnly.insert({str: "foo"}) WriteResult({ "nInserted" : 1 }) > db.stringsOnly.insert({str: 1}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 121, "errmsg" : "Document failed validation" } })
We will support draft 4 of the JSON Schema spec, as described by https://tools.ietf.org/html/draft-zyp-json-schema-04 and https://tools.ietf.org/html/draft-fge-json-schema-validation-00. However, we cannot claim to be fully compliant with draft 4, since MongoDB's initial schema support will omit the following:
- Hypermedia and linking properties of JSON Schema. The use of JSON References and JSON Pointers will not be supported.
- Meta-validation of the schema specification via "$schema", a special JSON Schema-specific keyword that self-describes the schema itself. This keyword will be explicitly rejected, as opposed to silently ignored.
- Semantic validation of strings via the "format" keyword.
We will support a few extensions to JSON schema which make sense for MongoDB. In particular, type validation will support not just number, integer, string, object, and array, but will also support the full list of BSON types.
- is duplicated by
-
SERVER-24846 disallow extra fields when validating documents
- Closed
- is related to
-
SERVER-1176 Unique index on array keys only
- Closed
- related to
-
SERVER-20718 $type should take an array of types to match against
- Closed