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

查看Validation 标签页
AtlasGoData Explorer在Atlas中,Go项目的 页面。
如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含项目的组织。
如果尚未显示,请从导航栏的 Projects 菜单中选择您的项目。
在侧边栏中,单击 Database 标题下的 Data Explorer。
显示数据浏览器。
注意
您也可以转到 Clusters 页面,然后单击 Shortcuts 标题下的 Data Explorer。
验证规则
验证编辑器支持JSON schema验证,以及使用查询运算符的查询表达式验证。单击 Update 按钮后, Atlas会更新以显示集合中通过验证的文档和未通过验证的文档。
JSON 模式验证
要指定 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" } } } }
此验证指定:
有关所有可用的 $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 Action 和 Validation Level:
验证操作确定是
warn
但接受无效文档,还是error
并拒绝无效文档。验证级别确定 MongoDB 将验证规则应用于现有文档的严格程度。
Strict
验证将您的规则应用于所有文档插入和更新。Moderate
验证仅将规则应用于新文档和现有的有效文档。现有的无效文档不受影响。
有关验证操作和级别的详细信息,请参阅 MongoDB 手册中的指定验证规则。
提示
限制
如果连接到 Atlas Data Federation,则 Validation(验证)标签页不可用。