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

绕过模式验证

本页内容

  • 上下文
  • 支持的操作
  • 先决条件
  • 步骤
  • 结果
  • 了解更多

在某些情况下,您可能需要绕过集合的模式验证规则。例如,如果您正在将可能无效的数据从备份恢复到具有验证规则的集合中。在这种情况下,旧文档可能不符合新的验证要求。

绕过模式验证是在每次操作的基础上进行的。如果您绕过模式验证来插入一个无效的文档,任何未来的无效文档更新必须

  • 也绕过模式验证

  • 结果产生一个有效的文档

您可以使用以下命令和方法在每次操作的基础上绕过验证

对于已启用访问控制的部署,为了绕过文档验证,认证用户必须具有 bypassDocumentValidation 操作。内置角色 dbAdminrestore 提供此操作。

以下示例创建一个具有模式验证的集合,然后通过绕过验证规则插入一个无效文档。

1

创建一个students集合,并使用$jsonSchema操作符设置模式验证规则

db.createCollection("students", {
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"
}
}
}
}
} )
2

以下文档无效,因为year字段超出了允许的范围(2017-3017

{
name: "Alice",
year: Int32( 2016 ),
major: "History",
gpa: Double(3.0),
address: {
city: "NYC",
street: "33rd Street"
}
}

要绕过验证规则并插入无效文档,请运行以下insert命令,将bypassDocumentValidation选项设置为true

db.runCommand( {
insert: "students",
documents: [
{
name: "Alice",
year: Int32( 2016 ),
major: "History",
gpa: Double(3.0),
address: {
city: "NYC",
street: "33rd Street"
}
}
],
bypassDocumentValidation: true
} )

要确认文档已成功插入,查询students集合

db.students.find()

MongoDB返回插入的文档

[
{
_id: ObjectId("62bcb4db3f7991ea4fc6830e"),
name: 'Alice',
year: 2016,
major: 'History',
gpa: 3,
address: { city: 'NYC', street: '33rd Street' }
}
]

返回

处理无效文档