查看现有验证规则
您可以查看集合的验证规则,以确定对文档施加了哪些限制以及MongoDB在发生无效文档时如何处理。
要查看集合的验证规则,请使用db.getCollectionInfos()
方法或 listCollections
数据库命令。
这两个命令返回相同的信息,但每个命令的输出格式不同。
先决条件
要在此页面上运行示例,请创建一个带有验证规则的 students
集合。有关更多信息,请参阅 指定 JSON Schema 验证。
示例: db.getCollectionInfos()
语法
以下命令使用 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' } } } }
示例:listCollections
语法
以下命令使用 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 }