Docs Home → Develop Applications → MongoDB Manual
On this page本页内容
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.db.getCollectionInfos()
方法或listCollections
数据库命令。
Both commands return the same information, but the output format differs between each command.两个命令都返回相同的信息,但每个命令的输出格式不同。
To run the examples on this page, create a 要运行此页面上的示例,请创建带有验证规则的students
collection with validation rules. students
集合。For more information, see Specify JSON Schema Validation.有关更多信息,请参阅指定JSON模式验证。
db.getCollectionInfos()
Syntaxdb.getCollectionInfos()
语法The 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' } } } }
If 如果未显式设置validationAction
and validationLevel
are not explicitly set, db.getCollectionInfos()
does not include those fields in its output.validationAction
和validationLevel
,则db.getCollectionInfos()
不会在其输出中包含这些字段。
listCollections
SyntaxlistCollections
语法The 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 }