Docs 菜单
Docs 主页
/
Compass
/

为模式设置验证规则

Validation (验证)标签页允许您管理集合的模式验证规则

模式验证可确保集合中的所有文档均遵循一组既定规则,例如符合特定的形状或只允许在字段中使用指定范围的值。

验证视图
点击放大

验证编辑器支持 JSON schema 验证,以及使用查询操作符验证的查询表达式验证。

$jsonSchema 操作符支持各种关键字,用于指定验证规则。例如:

  • required 数组可以定义文档中的必填字段。

  • properties 对象定义了特定文档字段的规则。

如要通过分析现有示例数据生成 JSON schema,请参阅生成验证规则。

考虑以下验证示例:

{
$jsonSchema: {
bsonType: "object",
required: [ "address", "borough", "name" ],
properties: {
address: {
bsonType: "object",
properties: {
coord: {
bsonType: "array",
items: [
{
bsonType: "double",
minimum: -180,
maximum: 180,
exclusiveMaximum: false,
description: "must be a number in [ -180, 180 ]"
},
{
bsonType: "double",
minimum: -90,
maximum: 90,
exclusiveMaximum: false,
description: "must be a number in [ -90, 90 ]"
}
]
}
},
description: "must be an object"
},
borough: {
bsonType: "string",
enum: [ "Manhattan", "Brooklyn", "Queens", "Bronx", "Staten Island" ],
description: "must be one of the enum strings"
}
}
}
}

此验证指定:

有关所有可用的 $jsonSchema 关键字,请参阅 MongoDB 手册中的 $jsonSchema 页面。

您也可以使用查询操作符来指定验证,但以下查询操作符除外:$near$nearSphere$text$where.

{
$or: [
{ name: { $type: "string" } },
{ borough: {
bsonType: "string",
enum: [ "Manhattan", "Brooklyn", "Queens", "Bronx", "Staten Island" ],
description: "must be one of the enum strings"
} }
]
}

使用此验证时,以下条件之一必须为 true:

  • name 字段必须是 BSON 类型字符串。

  • borough 字段必须是枚举字符串之一。

在顶部指定 Validation ActionValidation Level

  • 验证操作确定是warn但接受无效文档,还是error并拒绝无效文档。

  • 验证级别确定 MongoDB 将验证规则应用于现有文档的严格程度。

    • Strict 验证将您的规则应用于所有文档插入和更新。

    • Moderate 验证仅将规则应用于新文档和现有的有效文档。现有的无效文档不受影响。

有关验证操作和级别的详细信息,请参阅 MongoDB 手册中的指定验证规则

如果连接到 Atlas Data Federation,则 Validation(验证)标签页不可用。

Compass 无法验证具有超过 1000 个不重复字段的模式。如果您尝试验证具有超过 1000 个不重复字段的模式,Compass 将会返回错误。

MongoDB Compass Readonly Edition 中,您只能查看验证规则。不允许创建和编辑验证规则。

后退

性能见解

在此页面上