ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

허용된 필드 값 지정

이 페이지의 내용

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. Similarly, you can use this functionality to prevent human error, such as typos, when inserting data into a collection.

To specify a list of allowed values, use the enum keyword in your JSON schema. The enum keyword means "enumerate", and is used to list possible values of a field.

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

0} 컬렉션을 $jsonSchema 만들고 shipping 연산자를 사용하여 스키마 유효성 검사 규칙을 설정합니다.

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.

2

The following insert operation fails because country is Germany, which isn't in the list of allowed values.

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

이 작업은 다음 오류를 반환합니다.

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

The insert succeeds after you change the country field to one of the allowed values:

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

문서가 성공적으로 삽입되었는지 확인하려면 shipping 컬렉션을 쿼리합니다.

db.shipping.find()

MongoDB returns the document:

[
{
_id: ObjectId("630d10d5931191850b40d0ab"),
item: 'sweater',
size: 'medium',
country: 'France'
}
]

이 페이지의 내용