Specify JSON Schema Validation指定JSON架构验证
On this page本页内容
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. JSON模式是一个词汇表,允许您对JSON文档进行注释和验证。You can use JSON schema to specify validation rules for your fields in a human-readable format.您可以使用JSON模式以可读格式为字段指定验证规则。
Context上下文
MongoDB supports draft 4 of JSON Schema, including core specificationMongoDB支持JSONSchema的草案4,包括核心规范 and validation specification
, with some differences.
和验证规范
,但有一些不同。
For details, see Extensions and Omissions.有关详细信息,请参阅扩展和省略。
For more information about JSON Schema, see the official website.有关JSON模式的更多信息,请参阅官方网站。
Restrictions限制
You can't specify schema validation for:不能为以下项指定架构验证:
Collections in theadmin
,local
, andconfig
databasesadmin
数据库、local
数据库和config
数据库中的集合System collections系统集合
Steps步骤
In this example, you create a 在本例中,您将创建一个具有验证规则的students
collection with validation rules and observe the results after you attempt to insert an invalid document.students
集合,并在尝试插入无效文档后观察结果。
Create a collection with validation.创建一个经过验证的集合。
Create a 创建一个students
collection and use the $jsonSchema
operator to set schema validation rules. students
集合,并使用$jsonSchema
运算符设置模式验证规则。For example:例如:
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
title: "Student Object Validation",
required: [ "address", "major", "name", "year" ],
properties: {
name: {
bsonType: "string",
description: "'name' must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "'year' must be an integer in [ 2017, 3017 ] and is required"
},
gpa: {
bsonType: [ "double" ],
description: "'gpa' must be a double if the field exists"
}
}
}
}
} )
Clarify Rules with Title and Description Fields用标题和描述字段澄清规则
You can use 当验证规则没有立即明确时,可以使用title
and description
fields to provide an explanation of validation rules when the rules are not immediately clear. title
和description
字段来提供对验证规则的解释。When a document fails validation, MongoDB includes these fields in the error output.当文档验证失败时,MongoDB会在错误输出中包含这些字段。
Confirm that the validation prevents invalid documents.确认验证可以防止无效文档。
The following insert operation fails because 以下插入操作失败,因为当gpa
is an integer when the validator
requires a double
.validator
需要double
时,gpa
是一个整数。
db.students.insertOne( {
name: "Alice",
year: Int32( 2019 ),
major: "History",
gpa: Int32(3),
address: {
city: "NYC",
street: "33rd Street"
}
} )
The operation returns this error:操作返回此错误:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("630d093a931191850b40d0a9"),
details: {
operatorName: '$jsonSchema',
title: 'Student Object Validation',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'gpa',
description: "'gpa' must be a double if the field exists",
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: [ 'double' ] },
reason: 'type did not match',
consideredValue: 3,
consideredType: 'int'
}
]
}
]
}
]
}
}
Query for the valid document.查询有效文档。
To confirm that the document was successfully inserted, query the 若要确认文档已成功插入,请查询students
collection:students
集合:
db.students.find()
MongoDB returns the inserted document:MongoDB返回插入的文档:
[
{
_id: ObjectId("62bb413014b92d148400f7a5"),
name: 'Alice',
year: 2019,
major: 'History',
gpa: 3,
address: { city: 'NYC', street: '33rd Street' }
}
]
Additional Information附加信息
You can combine JSON Schema validation with query operator validation.您可以将JSON模式验证与查询运算符验证相结合。
For example, consider a 例如,考虑一个具有此模式验证的sales
collection with this schema validation:sales
集合:
db.createCollection("sales", {
validator: {
"$and": [
// Validation with query operators
{
"$expr": {
"$lt": ["$lineItems.discountedPrice", "$lineItems.price"]
}
},
// Validation with JSON Schema
{
"$jsonSchema": {
"properties": {
"items": { "bsonType": "array" }
}
}
}
]
}
}
)
The preceding validation enforces these rules for documents in the 前面的验证对sales
collection:sales
集合中的文档强制执行以下规则:
lineItems.discountedPrice
must be less than必须小于lineItems.price
.lineItems.price
。This rule is specified using the此规则是使用$lt
operator.$lt
运算符指定的。Theitems
field must be an array.items
字段必须是一个数组。This rule is specified using此规则是使用$jsonSchema
.$jsonSchema
指定的。
Learn More了解更多信息
To see the complete list of allowed keywords in a JSON schema, see Available Keywords.要查看JSON模式中允许的键的完整列表,请参阅可用键。To restrict what values a certain field can contain, see Specify Allowed Field Values.要限制某个字段可以包含的值,请参阅指定允许的字段值。To avoid issues with JSON schema validation, see Tips for JSON Schema Validation.为了避免JSON模式验证问题,请参阅JSON模式验证提示。