Docs HomeDevelop ApplicationsMongoDB Manual

Modify Schema Validation修改架构验证

On this page本页内容

After you add schema validation to a collection, you can modify your schema validation at any time. 将架构验证添加到集合后,可以随时修改架构验证。For example, you may decide:例如,您可以决定:

To modify a collection's schema validation, use the collMod command and specify the updated validation in the validator object.要修改集合的模式验证,请使用collMod命令并在验证器对象中指定更新的验证。

Context上下文

You can modify all components of a schema validation, including its rules, validation level, and validation action.您可以修改架构验证的所有组件,包括其规则、验证级别和验证操作。

If you update a collection's validation rules, documents inserted prior to the validation change may no longer be valid. 如果更新集合的验证规则,则在验证更改之前插入的文档可能不再有效。How MongoDB handles these invalid documents depends on your validationLevel. MongoDB如何处理这些无效文档取决于您的validationLevelBy default, MongoDB applies validation checks to all documents, regardless of when they were inserted.默认情况下,MongoDB对所有文档应用验证检查,而不管它们是何时插入的。

Steps步骤

The following procedure creates a collection with validation rules and then modifies those rules. 以下过程创建一个包含验证规则的集合,然后修改这些规则。You will observe the results when inserting an invalid and valid document.插入无效和有效的文档时,您将观察结果。

1

Create a collection with validation.创建带有验证的集合。

Create a users collection with validation rules:使用验证规则创建users集合:

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

Modify the validation schema.修改验证架构。

Run the following collMod command to change the minLength of the password field from 8 to 12:运行以下collMod命令将password字段的minLength8更改为12

db.runCommand( { collMod: "users",
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "username", "password" ],
         properties: {
            name: {
               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"
            }
         }
      }
   }
} )
Tip提示

You can also use the collMod command to add validation to an existing collection that was not created with validation.您还可以使用collMod命令向未使用验证创建的现有集合添加验证。

Results结果

The following examples show what happens when you insert a valid and invalid document into the users collection, and how to handle previously valid documents that are no longer valid as a result of changes to the validation rules.以下示例显示了在用户集合中插入有效和无效文档时会发生什么,以及如何处理由于更改验证规则而不再有效的以前有效的文档。

Insert an Invalid Document插入无效文档

The following operation attempts to insert an invalid document. 以下操作试图插入无效文档。The document is invalid because the password field is 10 characters long when the minimum length is 12:文档无效,因为当最小长度为12时,password字段长度为10个字符:

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

MongoDB returns the following error:MongoDB返回以下错误:

MongoServerError: Document failed validation
Additional 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'
              }
            ]
          }
        ]
      }
    ]
  }
}

Insert a Valid Document插入有效文档

The following operation inserts a valid document, where the password field is at least 12 characters long:以下操作将插入有效文档,其中password字段至少为12个字符:

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

Handle a Previously Valid Document That Is No Longer Valid处理以前有效但不再有效的文档

Consider the following document that is valid for the first version of the schema validation, but not the second:请考虑以下文档,该文档对模式验证的第一个版本有效,但对第二个版本无效:

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

The document's password field is 10 characters. 文档的password字段为10个字符。The first version of the schema validation required a minimum of 8 characters, meaning this document was valid. 第一个版本的模式验证要求至少8个字符,这意味着该文档是有效的。However, after updating the validation to require the password to be a minimum of 12 characters, the document is no longer valid.但是,在更新验证以要求password至少为12个字符后,该文档不再有效。

When a change in schema validation causes previously valid documents to become invalid, the newly invalid documents remain in the collection.当架构验证中的更改导致以前有效的文档变为无效时,新的无效文档将保留在集合中。

The way MongoDB handles newly invalid documents depends on the schema's validationLevel. MongoDB处理新的无效文档的方式取决于模式的validationLevelThe schema validation in this example uses the default validationLevel of strict, meaning the document must match the new validation rules. 本例中的模式验证使用默认的validationLevel strict,这意味着文档必须与新的验证规则匹配。MongoDB checks the validation each time the document is updated.每次更新文档时,MongoDB都会检查验证。

If the updated schema validation had a validationLevel of moderate, this document would not need to match the new validation rules.如果更新的模式验证的validationLevelmoderate,则此文档不需要匹配新的验证规则。

Learn More

←  View Existing Validation Rules查看现有验证规则Specify Validation Level for Existing Documents指定现有文档的验证级别 →