文档菜单
文档首页
/
MongoDB Compass
/

为您的模式设置验证规则

本页内容

  • 验证选项卡
  • 验证规则
  • 验证操作和级别
  • 限制

验证验证选项卡允许您管理集合的验证规则

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

Validation view
点击放大

验证编辑器支持 JSON Schema 验证,以及使用 查询操作符 的查询表达式验证。点击 更新 按钮后,Compass 将更新以显示通过验证和未通过验证的文档。

要指定 JSON Schema 验证,请使用 $jsonSchema 操作符。

{
$jsonSchema: {
required: ['name', 'borough'], // the name and borough fields are required
properties: {
cuisine: {
bsonType: "string",
description: "must be a string"
}
}
}
}

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

  • 验证required 数组定义了文档中必需的字段。

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

以下是一个示例验证

{
$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"
}
}
}
}

此验证指定了

  • 必需字段的列表。

  • 所有必需字段的 bsonType

  • address.coord 数组中的 minimummaximum 值。

  • 字段 borough 的可接受值,使用 enum.

有关所有可用的 $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"
} }
]
}

使用此验证,以下条件之一必须为真

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

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

在顶部指定一个验证操作验证级别

  • 验证操作决定了是否警告但接受无效文档,或错误地拒绝无效文档。

  • 验证级别决定了MongoDB如何严格地将验证规则应用于现有文档。

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

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

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

提示

另请参阅

如果您连接到Atlas数据联邦。,则无法访问验证选项卡。

MongoDB Compass只读版中,您只能查看验证规则。不允许创建和编辑验证规则。.. 仅限-COMPASS

返回

性能洞察