You can view a collection's validation rules to determine what restrictions are imposed on documents and how MongoDB handles invalid documents when they occur.您可以查看集合的验证规则,以确定对文档施加了哪些限制,以及MongoDB如何处理出现的无效文档。
To view a collection's validation rules, use the db.getCollectionInfos() method or listCollections database command.
Both commands return the same information, but the output format differs between each command.两个命令返回相同的信息,但每个命令的输出格式不同。
Prerequisite先决条件
To run the examples on this page, create a 要运行此页面上的示例,请使用验证规则创建一个students collection with validation rules. For more information, see Specify JSON Schema Validation.students集合。有关更多信息,请参阅指定JSON模式验证。
Example: db.getCollectionInfos() Syntax示例:db.getCollectionInfos()语法
db.getCollectionInfos() SyntaxThe following command uses 以下命令使用db.getCollectionInfos() to return the validation rules for the students collection:db.getCollectionInfos()返回students集合的验证规则:
db.getCollectionInfos( { name: "students" } )[0].options.validator
The output resembles the following validation object:输出类似于以下验证对象:
{
'$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'
}
}
}
}
Note
Validation Action and Level Not Included by Default默认情况下不包括验证操作和级别
If 如果未显式设置validationAction and validationLevel are not explicitly set, db.getCollectionInfos() does not include those fields in its output.validationAction和validationLevel,db.getCollectionInfos()不会在其输出中包含这些字段。
Example: listCollections Syntax示例:listCollections语法
listCollections SyntaxThe following command uses 以下命令使用listCollections to return the validation rules for the students collection:listCollections返回students集合的验证规则:
db.runCommand ( { listCollections: 1, filter: { name: "students" } } )
The output resembles the following object:输出类似于以下对象:
{
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
}