“文档” 菜单
文档首页
/
MongoDB Manual
/ /

查看现有验证规则

在此页面上

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

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

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

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

要运行此页面上的示例,请创建包含验证规则的 students 集合。有关更多信息,请参阅指定 JSON 模式验证。

以下命令使用 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'
}
}
}
}

注意

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

如果未显式设置 validationActionvalidationLeveldb.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
}
← 使用查询运算符指定验证