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

查看现有验证规则

本页内容

  • 先决条件
  • 示例db.getCollectionInfos() 语法
  • 示例:listCollections 语法
  • 了解更多

您可以查看集合的验证规则,以确定对文档施加了哪些限制以及MongoDB在发生无效文档时如何处理。

要查看集合的验证规则,请使用db.getCollectionInfos() 方法或 listCollections 数据库命令。

这两个命令返回相同的信息,但每个命令的输出格式不同。

要在此页面上运行示例,请创建一个带有验证规则的 students 集合。有关更多信息,请参阅 指定 JSON Schema 验证。

以下命令使用 db.getCollectionInfos() 返回 students 集合的验证规则

db.getCollectionInfos( { name: "students" } )[0].options.validator

输出类似于以下验证对象

{
'$jsonSchema': {
bsonType: 'object',
required: [ 'name', 'year', 'major', 'address' ],
properties: {
name: {
bsonType: 'string',
description: 'must be a string and is required'
},
year: {
bsonType: 'int',
minimum: 2017,
maximum: 3017,
description: 'must be an integer in [ 2017, 3017 ] and is required'
},
gpa: {
bsonType: [ 'double' ],
description: 'must be a double if the field exists'
}
}
}
}

注意

默认情况下不包含验证操作和级别

如果未显式设置 validationActionvalidationLevel,则 db.getCollectionInfos() 不会将其包含在输出中。

以下命令使用 listCollections 返回 students 集合的验证规则

db.runCommand ( { listCollections: 1, filter: { name: "students" } } )

输出类似于以下对象

{
cursor: {
id: Long("0"),
ns: 'test.$cmd.listCollections',
firstBatch: [
{
name: 'students',
type: 'collection',
options: {
validator: {
'$jsonSchema': {
bsonType: 'object',
required: [ 'name', 'year', 'major', 'address' ],
properties: {
name: {
bsonType: 'string',
description: 'must be a string and is required'
},
gpa: {
bsonType: [ 'double' ],
description: 'must be a double if the field exists'
}
}
},
validationAction: 'warn'
}
},
info: {
readOnly: false,
uuid: UUID("bf560865-5879-4ec1-b389-f77a03abbc5a")
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
}
]
},
ok: 1
}

返回

绕过