Docs HomeMongoDB Manual

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

You can specify validation using query operators such as $eq and $gt to compare fields.您可以使用查询运算符(如$eq$gt)指定验证以比较字段。

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. 订单有底价和VATThe 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: NumberDecimal("141"),
VAT: NumberDecimal("0.20"),
totalWithVAT: NumberDecimal("169")
} )

141 * (1 + 0.20) equals 169.2, so the value of the totalWithVAT field must be 169.2.141*(1+0.20)等于169.2,因此totalWithVAT字段的值必须为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: NumberDecimal("141"),
VAT: NumberDecimal("0.20"),
totalWithVAT: NumberDecimal("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使用JSON架构进行验证
{
"$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 Selectors.要查看MongoDB中可用的所有查询运算符,请参阅查询选择器
  • To learn more about the $expr operator, which allows the use of aggregation expressions within the query language, see $expr.要了解有关$expr运算符的更多信息,请参阅$expr,该运算符允许在查询语言中使用聚合表达式。