$jsonSchema

On this page本页内容

Definition定义

$jsonSchema

New in version 3.6.3.6版中的新增。

The $jsonSchema operator matches documents that satisfy the specified JSON Schema.$jsonSchema运算符匹配满足指定JSON架构的文档。

The $jsonSchema operator expression has the following syntax:$jsonSchema运算符表达式具有以下语法:

{ $jsonSchema: <JSON Schema object> }

Where the JSON Schema object is formatted according to draft 4 of the JSON Schema standard.其中,JSON架构对象根据JSON架构标准草案4进行格式化。

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

For example:例如:

{
  $jsonSchema: {
     required: [ "name", "major", "gpa", "address" ],
     properties: {
        name: {
           bsonType: "string",
           description: "must be a string and is required"
        },
        address: {
           bsonType: "object",
           required: [ "zipcode" ],
           properties: {
               "street": { bsonType: "string" },
               "zipcode": { bsonType: "string" }
           }
        }
     }
  }
}

For a list of keywords supported by MongoDB, see Available Keywords.有关MongoDB支持的关键字列表,请参阅可用关键字

Note

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences.MongoDB支持JSON架构草案4,包括核心规范校验规范,但有一些不同。See Extensions and Omissions for details.有关详细信息,请参阅扩展省略

For more information about JSON Schema, see the official website.有关JSON架构的更多信息,请参阅官方网站

Behavior行为

Feature Compatibility功能兼容性

The featureCompatibilityVersion must be set to "3.6" or higher in order to use $jsonSchema.要使用$jsonSchema,必须将featureCompatibilityVersion设置为“3.6”或更高。

Document Validator文档校验器

You can use $jsonSchema in a document validator to enforce the specified schema on insert and update operations:您可以在文档校验器中使用$jsonSchema在插入和更新操作中强制执行指定的架构:

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

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:您可以在读写操作的查询条件中使用$jsonSchema来查找集合中满足指定架构的文档:

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

To find documents in the collection that do not satisfy the specified schema, use the $jsonSchema expression in a $nor expression.要查找集合中不满足指定架构的文档,请在$nor表达式中使用$jsonSchema表达式。For example:例如:

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

Examples示例

Schema Validation架构校验

The following db.createCollection() method creates a collection named students and uses the $jsonSchema operator to set schema validation rules:以下db.createCollection()方法创建名为students的集合,并使用$jsonSchema运算符设置架构校验规则:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     "description": "must be a string and is required"
                  }
               }
            }
         }
      }
   }
})

Given the created validator for the collection, the following insert operation will fail because gpa is an integer when the validator requires a double.给定为集合创建的validator,以下插入操作将失败,因为validator需要double,而gpa是整数。

db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: NumberInt(3),
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

The operation returns the following error:该操作返回以下错误:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"
   }
})

After changing the gpa to a double, the insert succeeds:gpa更改为双精度后,插入成功:

db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: 3.0,
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

The operation returns the following:该操作返回以下内容:

WriteResult({ "nInserted" : 1 })

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.您可以在读写操作的查询条件中使用$jsonSchema来查找集合中满足指定架构的文档。

For example, create a sample collection inventory with the following documents:例如,使用以下文档创建样本集合inventory

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

Next, define the following sample schema object:接下来,定义以下示例架构对象:

let myschema =  {
      required: [ "item", "qty", "instock" ],
      properties: {
         item: { bsonType: "string" },
         qty: { bsonType: "int" },
         size: {
            bsonType: "object",
            required: [ "uom" ],
            properties: {
               uom: { bsonType: "string" },
               h: { bsonType: "double" },
               w: { bsonType: "double" }
            }
          },
          instock: { bsonType: "bool" }
      }
 }

You can use $jsonSchema to find all documents in the collection that satisfy the schema:您可以使用$jsonSchema查找集合中满足架构的所有文档:

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

You can use $jsonSchema with the $nor to find all documents that do not satisfy the schema:您可以将$jsonSchema$nor一起使用,以查找所有不符合架构的文档:

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

Or, you can update all documents that do not satisfy the schema:或者,您可以更新所有不满足架构的文档:

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

Or, you can delete all documents that do not satisfy the schema:或者,您可以删除所有不符合架构的文档:

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

JSON SchemaJSON架构

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences.MongoDB支持JSON架构草案4,包括核心规范校验规范,但有一些不同。See Extensions and Omissions for details.有关详细信息,请参阅扩展省略

For more information about JSON Schema, see the official website.有关JSON架构的更多信息,请参阅官方网站

Available Keywords可用关键字

Note

MongoDB implements a subset of keywords available in JSON Schema. For a complete list of omissions, see Omissions.MongoDB实现了JSON架构中可用的关键字子集。有关遗漏的完整列表,请参阅遗漏

Keyword关键词Type类型Definition释义Behavior行为
bsonType all types所有类型 string alias or array of string aliases字符串别名或字符串别名数组 Accepts same string aliases used for the $type operator接受与$type运算符相同的字符串别名
enum all types所有类型 array of values值数组 Enumerates all possible values of the field枚举字段的所有可能值
type all types所有类型 string or array of unique strings字符串或唯一字符串数组

Enumerates the possible JSON types of the field.枚举字段的可能JSON类型。Available types are “object”, “array”, “number”, “boolean”, “string”, and “null”.可用的类型有“对象”、“数组”、“数字”、“布尔”、“字符串”和“空”。

MongoDB’s implementation of the JSON Schema does not support the “integer” type.MongoDB的JSON架构实现不支持“integer”类型。Use the bsonType keyword and the “int” or “long” types instead.改用bsonType关键字和“int”或“long”类型。

allOf all types所有类型 array of JSON Schema objectsJSON架构对象数组 Field must match all specified schemas字段必须匹配所有指定的架构
anyOf all types所有类型 array of JSON Schema objectsJSON架构对象数组 Field must match at least one of the specified schemas字段必须至少匹配一个指定的架构
oneOf all types所有类型 array of JSON Schema objectsJSON架构对象数组 Field must match exactly one of the specified schemas字段必须与指定的架构中的一个完全匹配
not all types所有类型 a JSON Schema objectJSON架构对象 Field must not match the schema字段不能与架构匹配
multipleOf numbers number Field must be a multiple of this value字段必须是此值的倍数
maximum numbers number Indicates the maximum value of the field指示字段的最大值
exclusiveMaximum numbers boolean If true and field is a number, maximum is an exclusive maximum. Otherwise, it is an inclusive maximum.如果为true且字段为数字,则maximum为排除式最大值。否则,它是一个包含式最大值。
minimum numbers number Indicates the minimum value of the field指示字段的最小值
exclusiveMinimum numbers boolean If true, minimum is an exclusive minimum. Otherwise, it is an inclusive minimum.如果为true,则minimum为排除式最小值。否则,它是一个包含式最小值。
maxLength strings integer Indicates the maximum length of the field指示字段的最大长度
minLength strings integer Indicates the minimum length of the field指示字段的最小长度
pattern strings string containing a regex包含正则表达式的字符串 Field must match the regular expression字段必须与正则表达式匹配
maxProperties objects integer Indicates the field’s maximum number of properties指示字段的最大属性数
minProperties objects integer Indicates the field’s minimum number of properties指示字段的最小属性数
required objects array of unique strings Object’s property set must contain all the specified elements in the array对象的属性集必须包含数组中的所有指定元素
additionalProperties objects boolean or object

If true, additional fields are allowed.如果为true,则允许其他字段。If false, they are not.如果为false,则不允许。If a valid JSON Schema object is specified, additional fields must validate against the schema.如果指定了有效的JSON架构对象,则必须根据该架构校验其他字段。

Defaults to true.默认为true

properties objects object A valid JSON Schema where each value is also a valid JSON Schema object一个有效的JSON架构,其中每个值也是一个有效的JSON架构对象
patternProperties objects object In addition to properties requirements, each property name of this object must be a valid regular expression除了properties要求外,此对象的每个属性名称必须是有效的正则表达式
dependencies objects object Describes field or schema dependencies描述字段或架构依赖项
additionalItems arrays boolean or object If an object, must be a valid JSON Schema如果是对象,则必须是有效的JSON架构
items arrays object or array Must be either a valid JSON Schema, or an array of valid JSON Schemas必须是有效的JSON架构或有效JSON架构数组
maxItems arrays integer Indicates the maximum length of array指示数组的最大长度
minItems arrays integer Indicates the minimum length of array指示数组的最小长度
uniqueItems arrays boolean If true, each item in the array must be unique. Otherwise, no uniqueness constraint is enforced.如果为true,则数组中的每个项都必须是唯一的。否则,不会强制执行唯一性约束。
title N/A string A descriptive title string with no effect.没有效果的描述性标题字符串。
description N/A string A string that describes the schema and has no effect.描述架构且不起作用的字符串。

Extensions扩展

MongoDB’s implementation of JSON Schema includes the addition of the bsonType keyword, which allows you to use all BSON types in the $jsonSchema operator.MongoDB对JSON架构的实现包括添加bsonType关键字,它允许您在$jsonSchema操作符中使用所有BSON类型。bsonType accepts the same string aliases used for the $type operator.bsonType接受与$type运算符相同的字符串别名。

Omissions遗漏

The following are not supported in MongoDB’s implementation of JSON Schema:MongoDB的JSON架构实现不支持以下内容:

  • Hypertext definitions in draft 4 of the JSON Schema spec.JSON模式规范草案4中的超文本定义
  • The keywords:关键词:
    • $ref
    • $schema
    • default
    • definitions
    • format
    • id
  • The integer type. You must use the BSON type int or long with the bsonType keyword.integer类型。必须将BSON类型intlongbsonType关键字一起使用。
  • Hypermedia and linking properties of JSON Schema, including the use of JSON References and JSON Pointers.JSON架构的超媒体和链接属性,包括JSON引用和JSON指针的使用。
  • Unknown keywords.未知关键字。