Database Manual / Data Modeling / Schema Validation

Specify Validation With Query Operators使用查询运算符指定验证

You can specify validation using query operators such as $eq and $gt to compare fields.

A common use case for schema validation with query operators is when you want to create dynamic validation rules that compare multiple field values at runtime. For example, if you have a field that depends on the value of another field and need to ensure that those values are correctly proportional to each other.使用查询运算符进行模式验证的一个常见用例是,当您想要创建在运行时比较多个字段值的动态验证规则时。例如,如果您有一个字段依赖于另一个字段的值,并且需要确保这些值彼此正确成比例。

Restrictions限制

Context上下文

Consider an application that tracks customer orders. The orders have a base price and a VAT. The orders collection contains these fields to track total price:考虑一个跟踪客户订单的应用程序。订单底价和增值税。orders集合包含以下字段以跟踪总价:

  • price
  • VAT
  • totalWithVAT

Steps步骤

The following procedure creates a schema validation with query operators to ensure that totalWithVAT matches the expected combination of price and VAT.以下过程使用查询运算符创建模式验证,以确保totalWithVAT与预期的priceVAT(增值税)组合相匹配。

1

Create a collection with validation.创建具有验证功能的集合。

Create an orders collection with schema validation:使用架构验证创建orders集合:

db.createCollection( "orders",
{
validator: {
$expr:
{
$eq: [
"$totalWithVAT",
{ $multiply: [ "$total", { $sum:[ 1, "$VAT" ] } ] }
]
}
}
}
)

With this validation, you can only insert documents if the totalWithVAT field equals total * (1 + VAT).通过此验证,只有当totalWithVAT字段等于total * (1 + VAT)时,您才能插入文档。

2

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

The following operation fails because the totalWithVAT field does not equal the correct value:以下操作失败,因为totalWithVAT字段不等于正确的值:

db.orders.insertOne( {
total: Decimal128("141"),
VAT: Decimal128("0.20"),
totalWithVAT: Decimal128("169")
} )

141 * (1 + 0.20) equals 169.2, so the value of the totalWithVAT field must be 169.2.

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

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("62bcc9b073c105dde9231293"),
details: {
operatorName: '$expr',
specifiedAs: {
'$expr': {
'$eq': [
'$totalWithVAT',
{
'$multiply': [ '$total', { '$sum': [ 1, '$VAT' ] } ]
}
]
}
},
reason: 'expression did not match',
expressionResult: false
}
}
3

Make the document valid and insert it.使文档有效并插入。

After updating the document to have the correct totalWithVAT value, the operation succeeds:将文档更新为具有正确的totalWithVAT值后,操作成功:

db.orders.insertOne( {
total: Decimal128("141"),
VAT: Decimal128("0.20"),
totalWithVAT: Decimal128("169.2")
} )

MongoDB returns the following output, indicating that the insert was successful:MongoDB返回以下输出,表示插入成功:

{
acknowledged: true,
insertedId: ObjectId("6304f4651e52f124b84479ba")
}

Additional Information附加信息

You can combine query operator validation with JSON Schema validation.您可以将查询运算符验证与JSON模式验证相结合

For example, consider a sales collection with this schema validation:例如,考虑一个具有此模式验证的sales集合:

 db.createCollection("sales", {
validator: {
"$and": [
// Validation with query operators
{
"$expr": {
"$lt": ["$lineItems.discountedPrice", "$lineItems.price"]
}
},
// Validation with JSON Schema
{
"$jsonSchema": {
"properties": {
"items": { "bsonType": "array" }
}
}
}
]
}
}
)

The preceding validation enforces these rules for documents in the sales collection:前面的验证对sales集合中的文档强制执行以下规则:

  • lineItems.discountedPrice must be less than lineItems.price. 必须小于lineItems.priceThis rule is specified using the $lt operator.此规则使用$lt运算符指定。
  • The items field must be an array. This rule is specified using $jsonSchema.items字段必须是数组。此规则使用$jsonSchema指定。

Learn More了解更多

  • To see all query operators available in MongoDB, see Query Predicates.要查看MongoDB中可用的所有查询运算符,请参阅查询谓词
  • To learn more about the $expr operator, which allows the use of aggregation expressions within the query language, see $expr.要了解有关$expr运算符的更多信息,该运算符允许在查询语言中使用聚合表达式,请参阅$expr