Database Manual / Data Modeling / Schema Validation

Specify JSON Schema Validation指定JSON架构验证

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. You can use JSON schema to specify validation rules for your fields in a human-readable format.JSON Schema是一个词汇表,允许您注释和验证JSON文档。您可以使用JSON模式以人类可读的格式为字段指定验证规则。

Compatibility兼容性

You can use JSON schema validation for deployments hosted in the following environments:您可以对以下环境中托管的部署使用JSON模式验证:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Context上下文

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences. For details, see Extensions and Omissions.MongoDB支持JSON Schema的草案4,包括核心规范验证规范,但存在一些差异。有关详细信息,请参阅扩展省略

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

Restrictions限制

You can't specify schema validation for:您不能为以下对象指定架构验证:

If you have Client-Side Field Level Encryption or Queryable Encryption enabled on a collection, validation is subject to the following restrictions:如果在集合上启用了客户端字段级加密可查询加密,则验证受以下限制:

  • For CSFLE, when running collMod, the libmongocrypt library prefers the the JSON encryption schema specified in the command. This enables setting a schema on a collection that does not yet have one.对于CSFLE,运行collMod时,libmongocrypt库更喜欢命令中指定的JSON加密模式。这允许在还没有架构的集合上设置架构。
  • For Queryable Encryption, any JSON schema that includes an encrypted field results in a query analysis error.对于可查询加密,任何包含加密字段的JSON模式都会导致查询分析错误。

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集合,并在尝试插入无效文档后观察结果。

1

Connect to your MongoDB deployment.连接到MongoDB部署。

To connect to a local MongoDB instance or MongoDB Atlas deployment using mongosh, refer to the steps in Connect to a Deployment or Connect via mongosh.要使用mongosh连接到本地MongoDB实例或MongoDB Atlas部署,请参阅连接到部署通过mongosh进行连接中的步骤。

2

Create a collection with validation.创建具有验证功能的集合。

In mongosh, run the following command to create a students collection and use the $jsonSchema operator to set schema validation rules:mongosh中,运行以下命令创建学生集合,并使用$jsonSchema运算符设置模式验证规则:

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

Tip

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. When a document fails validation, MongoDB includes these fields in the error output.当验证规则不明确时,您可以使用titledescription字段来提供验证规则的解释。当文档验证失败时,MongoDB会在错误输出中包含这些字段。

3

Confirm that the validation prevents invalid documents.确认验证可防止无效文档。

Run the following command. The 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"
}
} )
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'
}
]
}
]
}
]
}
}

Tip

By default, mongosh prints nested objects up to six levels deep. To print all nested objects to their full depth, set inspectDepth to Infinity.默认情况下,mongosh打印嵌套对象,深度可达六层。要将所有嵌套对象打印到其完整深度,请将inspectDepth设置为Infinity

config.set("inspectDepth", Infinity)
4

Insert a valid document.插入有效文档。

If you change the gpa field value to a double type, the insert operation succeeds. Run the following command to insert the valid document:如果将gpa字段值更改为double类型,则插入操作成功。运行以下命令以插入有效文档:

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

Query for the valid document.查询有效文档。

To confirm that you've successfully inserted the document, run the following command to query the students collection:要确认您已成功插入文档,请运行以下命令查询students集合:

db.students.find()
[
{
_id: ObjectId("62bb413014b92d148400f7a5"),
name: 'Alice',
year: 2019,
major: 'History',
gpa: 3,
address: { city: 'NYC', street: '33rd Street' }
}
]

Tip

If you're connected to an Atlas deployment, you can also view and filter for the document in the Atlas UI.如果您连接到Atlas部署,您还可以在Atlas UI中查看和筛选文档

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. This rule is specified using the $lt operator.必须小于lineItems.price。此规则使用$lt运算符指定。
  • The items field must be an array. This rule is specified using $jsonSchema.items字段必须是数组。此规则使用$jsonSchema指定。

Learn More了解更多