$jsonSchema

在本页面

Definition

$jsonSchema运算符匹配满足指定 JSON 模式的文档。

$jsonSchema运算符表达式具有以下语法:

{ $jsonSchema: <JSON Schema object> }

JSON Schema 对象根据JSON Schema 标准的草案 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" }
           }
        }
     }
  }
}

有关 MongoDB 支持的关键字列表,请参阅Available Keywords

Note

MongoDB 支持 JSON Schema 草案 4,包括core specificationvalidation specification,但有一些区别。有关详细信息,请参见ExtensionsOmissions

有关 JSON 模式的更多信息,请参见official website

Behavior

Feature Compatibility

featureCompatibilityVersion必须设置为"3.6"或更高版本才能使用$jsonSchema

Document Validator

您可以在文档验证器中使用$jsonSchema来对插入和更新操作强制执行指定的架构:

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

Query Conditions

您可以在查询条件中使用$jsonSchema进行读写操作,以在集合中查找满足指定架构的文档:

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

要在集合中查找不满足指定模式的文档,请在$nor表达式中使用$jsonSchema表达式。例如:

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

以下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"
                  }
               }
            }
         }
      }
   }
})

给定为集合创建的validator,以下插入操作将失败,因为当validator需要doublegpa是整数。

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

该操作返回以下错误:

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

gpa更改为双精度后,插入成功:

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

该操作返回以下内容:

WriteResult({ "nInserted" : 1 })

Query Conditions

您可以在查询条件中使用$jsonSchema进行读写操作,以在集合中查找满足指定架构的文档。

例如,使用以下文档创建 samples 集合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 }
])

接下来,定义以下示例架构对象:

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" }
      }
 }

您可以使用$jsonSchema查找集合中满足模式的所有文档:

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

您可以将$jsonSchema$nor一起使用,以查找不满足该架构的所有文档:

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

或者,您可以更新不满足该架构的所有文档:

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

或者,您可以删除所有不符合模式的文档:

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

JSON Schema

MongoDB 支持 JSON Schema 草案 4,包括core specificationvalidation specification,但有一些区别。有关详细信息,请参见ExtensionsOmissions

有关 JSON 模式的更多信息,请参见official website

Available Keywords

Note

MongoDB 实现了 JSON 模式中可用的关键字子集。有关遗漏的完整列表,请参见Omissions

Keyword Type Definition Behavior
bsonType all types 字符串别名或字符串别名数组 接受与$type运算符相同的string aliases
enum all types 值数组 枚举该字段的所有可能值
type all types 字符串或唯一字符串数组 枚举该字段的可能 JSON 类型。可用的类型为“对象”,“数组”,“数字”,“布尔”,“字符串”和“空”。


MongoDB 的 JSON Schema 实现不支持“整数”类型。使用bsonType关键字和“ int”或“ long”类型。
|| allOf |所有类型| JSON 模式对象数组|字段必须与所有指定的模式|匹配
|| anyOf |所有类型| JSON 模式对象数组|字段必须与至少一个指定模式匹配|
| oneOf |所有类型| JSON 模式对象的数组|字段必须与指定模式之一完全匹配|
|不是|所有类型| JSON 模式对象|字段不得与模式匹配|
| multipleOf | numbers | number |字段必须是该值的倍数|
| maximum |数字| number |表示字段的最大值|
| exclusiveMaximum | numbers | boolean |如果为 true 且 field 为数字,则maximum为互斥最大值。否则,它是一个包含性最大值。
| minimum |数字| number |表示字段的最小值|
| exclusiveMinimum |数字|布尔值|如果为 true,则minimum是互斥最小值。否则,它是一个包含性的最小值。
| maxLength | strings | integer |表示字段的最大长度|
| minLength | strings | integer |表示字段的最小长度|
| pattern | strings |包含正则表达式的字符串|字段必须匹配正则表达式|
| maxProperties | objects | integer |指示字段的最大属性数|
| minProperties | objects | integer |表示字段的最小属性数|
|必需|对象|唯一字符串数组|对象的属性集必须包含数组中所有指定的元素|
| additionalProperties | objects | boolean 或 object |如果true,则允许其他字段。如果false,则不是。如果指定了有效的 JSON 模式对象,则必须根据模式验证其他字段。
默认为true
| properties | objects | object |有效的 JSON 模式,其中每个值也是有效的 JSON 模式对象|
| patternProperties | objects | object |除了properties要求,此对象的每个属性名称都必须是有效的正则表达式|
|依赖性|对象|对象|描述字段或模式依赖性|
| additionalItems | arrays |布尔值或对象|如果是对象,则必须是有效的 JSON Schema |
|项|数组|对象或数组|必须是有效的 JSON 模式,或者是有效的 JSON 模式的数组|
| maxItems | arrays | integer |表示数组的最大长度|
| minItems | arrays | integer |表示数组的最小长度|
| uniqueItems |数组|布尔值|如果为 true,则数组中的每个项目都必须是唯一的。否则,不强制执行唯一性约束。
| title | N/A | string |无效的描述性标题字符串。
| description | N/A | string |描述模式的字符串,不起作用。

Extensions

MongoDB 的 JSON Schema 实现包括bsonType关键字,它使您可以在$jsonSchema运算符中使用所有BSON类型。 bsonType接受与$type运算符相同的字符串别名。

Omissions

MongoDB 的 JSON Schema 实现不支持以下内容:

首页