文档菜单
文档首页
/
MongoDB 手册
/ /

指定 JSON 模式验证

在本页

  • 兼容性
  • 上下文
  • 限制
  • 步骤
  • 更多信息
  • 了解更多

JSON 模式是一种词汇,允许您注解和验证 JSON 文档。您可以使用 JSON 模式以可读的格式指定字段的验证规则。

您可以使用JSON模式验证在以下环境中部署

  • MongoDB Atlas:MongoDB在云中部署的完全托管服务

  • MongoDB Enterprise:基于订阅的自托管MongoDB版本

  • MongoDB Community:源代码开放、免费使用且自托管MongoDB版本

MongoDB 支持JSON Schema的第4个草案,包括核心规范验证规范,有一些不同之处。详细信息请参见扩展省略

有关JSON Schema的更多信息,请参阅官方网站

您不能为以下内容指定模式验证

  • adminlocalconfig数据库中的

  • 系统集合

如果您在一个集合上启用了客户端字段级加密可查询加密,验证将受到以下限制

  • 对于CSFLE,当运行collMod时,libmongocrypt库更喜欢命令中指定的JSON加密模式。这允许在尚未具有模式的集合上设置模式。

  • 对于可查询加密,任何包含加密字段的JSON模式都会导致查询分析错误。

在这个示例中,您创建一个具有验证规则的students集合,并在尝试插入一个无效的文档后观察结果。

1

要使用 mongosh 连接到本地 MongoDB 实例或 MongoDB Atlas 部署,请参考 连接到部署通过 mongosh 连接。

2

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

提示

使用标题和描述字段澄清规则

您可以使用 titledescription 字段来提供验证规则的解释,当规则不立即明显时。当文档验证失败时,MongoDB 将包括这些字段在错误输出中。

3

运行以下命令。插入操作失败,因为当验证器要求 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)
4

如果您将 gpa 字段值更改为 double 类型,则插入操作成功。运行以下命令插入有效文档:

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

要确认您已成功插入文档,运行以下命令查询 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 指定。

返回

模式验证