Docs HomeDevelop ApplicationsMongoDB Manual

Specify Allowed Field Values指定允许的字段值

On this page本页内容

When you create a JSON Schema, you can specify what values are allowed in a particular field. Use this functionality to ensure that your field values belong to an expected set of values, such as a list of countries. 创建JSON模式时,可以指定特定字段中允许的值。使用此功能可确保字段值属于预期的值集,例如国家列表。Similarly, you can use this functionality to prevent human error, such as typos, when inserting data into a collection.类似地,在将数据插入集合时,可以使用此功能防止人为错误,例如键入错误。

Context上下文

To specify a list of allowed values, use the enum keyword in your JSON schema. 要指定允许值的列表,请在JSON模式中使用enum关键字。The enum keyword means "enumerate", and is used to list possible values of a field.enum关键字表示“enumerate”,用于列出字段的可能值。

Steps步骤

Consider a clothing company that only ships products to France, the United Kingdom, and the United States. 以一家只向法国、英国和美国运送产品的服装公司为例。In the validator, you can list the allowed country values and reject documents that specify a different country.在验证器中,您可以列出允许的国家/地区值,并拒绝指定不同国家/地区的文档。

1

Create a collection with validation containing enum.使用包含enum的验证创建集合。

Create a shipping collection and use the $jsonSchema operator to set schema validation rules:创建一个shipping集合,并使用$jsonSchema运算符设置模式验证规则:

db.createCollection("shipping", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         title: "Shipping Country Validation",
         properties: {
            country: {
               enum: [ "France", "United Kingdom", "United States" ],
               description: "Must be either France, United Kingdom, or United States"
            }
         }
      }
   }
} )

The enum field in the country object only allows documents where the country field is either France, United Kingdom, or United States.country对象中的enum字段仅允许country字段为FranceUnited KingdomUnited States的文档。

2

Confirm that the validation prevents invalid documents.确认验证可防止无效文档。

The following insert operation fails because country is Germany, which isn't in the list of allowed values.以下插入操作失败,因为countryGermany,不在允许值列表中。

db.shipping.insertOne( {
   item: "sweater",
   size: "medium",
   country: "Germany"
} )

The operation returns this error:操作返回以下错误:

MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("630d1057931191850b40d0aa"),
  details: {
    operatorName: '$jsonSchema',
    title: 'Shipping Country Validation',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [
          {
            propertyName: 'country',
            description: 'Must be either France, United Kingdom, or United States',
            details: [
              {
                operatorName: 'enum',
                specifiedAs: {
                  enum: [ 'France', 'United Kingdom', 'United States' ]
                },
                reason: 'value was not found in enum',
                consideredValue: 'Germany'
              }
            ]
          }
        ]
      }
    ]
  }
}
3

Insert a valid document.插入有效文档。

The insert succeeds after you change the country field to one of the allowed values:country字段更改为允许的值之一后,插入成功:

db.shipping.insertOne( {
   item: "sweater",
   size: "medium",
   country: "France"
} )
4

Query for the valid document.查询有效文档。

To confirm that the document was successfully inserted, query the shipping collection:要确认文档已成功插入,请查询shipping集合:

db.shipping.find()

MongoDB returns the document:

[
  {
    _id: ObjectId("630d10d5931191850b40d0ab"),
    item: 'sweater',
    size: 'medium',
    country: 'France'
  }
]
←  Specify JSON Schema ValidationTips for JSON Schema Validation →