指定 JSON 模式验证
JSON 模式是一种词汇,允许您注解和验证 JSON 文档。您可以使用 JSON 模式以可读的格式指定字段的验证规则。
兼容性
您可以使用JSON模式验证在以下环境中部署
MongoDB Atlas:MongoDB在云中部署的完全托管服务
MongoDB Enterprise:基于订阅的自托管MongoDB版本
MongoDB Community:源代码开放、免费使用且自托管MongoDB版本
上下文
MongoDB 支持JSON Schema的第4个草案,包括核心规范和验证规范,有一些不同之处。详细信息请参见扩展和省略。
有关JSON Schema的更多信息,请参阅官方网站
限制
您不能为以下内容指定模式验证
在
admin
、local
和config
数据库中的
如果您在一个集合上启用了客户端字段级加密或可查询加密,验证将受到以下限制
对于CSFLE,当运行
collMod
时,libmongocrypt库更喜欢命令中指定的JSON加密模式。这允许在尚未具有模式的集合上设置模式。对于可查询加密,任何包含加密字段的JSON模式都会导致查询分析错误。
步骤
在这个示例中,您创建一个具有验证规则的students
集合,并在尝试插入一个无效的文档后观察结果。
连接到您的MongoDB部署。
要使用 mongosh
连接到本地 MongoDB 实例或 MongoDB Atlas 部署,请参考 连接到部署 或 通过 mongosh 连接。
创建具有验证的集合。
在 mongosh
中,运行以下命令创建一个 students
集合,并使用 $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" } } } } } )
提示
使用标题和描述字段澄清规则
您可以使用 title
和 description
字段来提供验证规则的解释,当规则不立即明显时。当文档验证失败时,MongoDB 将包括这些字段在错误输出中。
确认验证阻止了无效的文档。
运行以下命令。插入操作失败,因为当验证器要求 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' } ] } ] } ] } }
提示
默认情况下,mongosh
打印嵌套对象最多六层。要打印所有嵌套对象到它们的完整深度,将 inspectDepth
设置为 Infinity
。
config.set("inspectDepth", Infinity)
查询有效文档。
要确认您已成功插入文档,运行以下命令查询 students
集合
db.students.find()
[ { _id: ObjectId("62bb413014b92d148400f7a5"), name: 'Alice', year: 2019, major: 'History', gpa: 3, address: { city: 'NYC', street: '33rd Street' } } ]
提示
如果您连接到 Atlas 部署,您还可以在 Atlas UI 中 查看和筛选文档。
更多信息
您可以将 JSON Schema 验证与 查询运算符验证 结合使用。
例如,考虑一个具有以下架构验证的 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" } } } } ] } } )
前面的验证强制实施以下规则,用于 sales
集合中的文档
lineItems.discountedPrice
必须小于lineItems.price
。该规则使用$lt
运算符指定。items
字段必须是一个数组。该规则使用$jsonSchema
指定。
了解更多
要查看 JSON schema 中允许的关键字完整列表,请参阅 可用关键字。
要限制某个字段可以包含的值,请参阅 指定允许的字段值。
要避免 JSON schema 验证问题,请参阅 JSON Schema 验证提示。