对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

修改模式验证

将模式验证添加到集合后,可以随时修改验证规则。 例如,您可以决定:

  • users 集合中的文档不再需要电子邮件地址。

  • 将 password 字段的最小长度从 8 个字符增加到 12 个字符。

要修改集合的模式验证,请使用 collMod 命令,并在 validator 对象中指定更新后的验证。

您可以修改模式验证的所有组件,包括其规则、验证级别和验证操作。

如果更新集合的验证规则,则在验证更改之前插入的文档可能不再有效。MongoDB 如何处理这些无效文档取决于您的validationLevel。默认情况下,MongoDB 对所有文档应用验证检查,无论其何时插入。

以下流程创建了一个包含验证规则的集合,然后修改了这些规则。

1

创建附带验证规则的 users 集合:

db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: [ "username", "password" ], properties: { username: { bsonType: "string", description: "must be a string and is required" }, password: { bsonType: "string", minLength: 8, description: "must be a string at least 8 characters long, and is required" } } } }} )
2

运行以下 collMod 命令,将 password 字段的 minLength 从 8 改为 12:

db.runCommand( { collMod: "users", validator: { $jsonSchema: { bsonType: "object", required: [ "username", "password" ], properties: { username: { bsonType: "string", description: "must be a string and is required" }, password: { bsonType: "string", minLength: 12, description: "must be a string of at least 12 characters, and is required" } } } }} )

提示

还可以使用 collMod 命令,向未通过验证创建的现有集合添加验证。

以下部分显示了这些场景中更新后验证的结果:

  • 当插入无效文档时。

  • 当插入有效文档时。

  • 当先前有效的文档因验证规则更改而失效时。

以下操作试图插入无效文档。该文档无效,因为当最小长度为 12 时,password 字段的长度为 10 个字符:

db.users.insertOne( { "username": "salesAdmin01", "password": "kT9$j4wg#M" })

MongoDB 返回如下错误:

MongoServerError: Document failed validationAdditional information: { failingDocumentId: ObjectId("62be0adb73c105dde9231299"), details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'password', description: 'must be a string of at least 8 characters, and is required', details: [ { operatorName: 'minLength', specifiedAs: { minLength: 12 }, reason: 'specified string length was not satisfied', consideredValue: 'kT9$j4wg#M' } ] } ] } ] }}

以下操作插入一个有效文档,其中 password 字段的长度至少为 12 个字符:

db.users.insertOne( { "username": "salesAdmin01", "password": "8p&SQd7T90$KKx" })

考虑以下对第一个版本的模式验证有效但对第二个版本无效的文档:

db.users.insertOne( { "username": "salesAdmin02", "password": "i8U60*VyL8" })

该文档的 password 字段为 10 个字符。第一个版本的模式验证需要至少 8 个字符,这意味着该文档是有效的。但是,在更新验证后,要求 password 至少为 12 个字符,因此该文档不再有效。

当模式验证的更改导致先前有效的文档变得无效时,新的无效文档仍保留在集合中。

MongoDB 处理新出现的无效文档的方式取决于模式的 validationLevel。本示例中的模式验证使用了默认的 strict 的 validationLevel,这意味着文档必须符合新的验证规则。每次文档更新时,MongoDB 都会检查验证情况。

如果更新后模式验证的 validationLevel 为 moderate,则此文档不需要匹配新的验证规则。