Specify Validation With Query Operators使用查询运算符指定验证
On this page本页内容
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限制
You can't specify the following query operators in a不能在validatorobject:validator对象中指定以下查询运算符:You can't specify schema validation for:不能为以下项指定架构验证:Collections in theadmin,local, andconfigdatabasesadmin数据库、local数据库和config数据库中的集合System collections系统集合
Context上下文
Consider an application that tracks customer orders. 考虑一个跟踪客户订单的应用程序。The orders have a base price and a VAT. 订单有底价和VAT。The orders collection contains these fields to track total price:orders集合包含以下字段以跟踪总价:
priceVATtotalWithVAT
Steps步骤
The following procedure creates a schema validation with query operators to ensure that 以下过程使用查询运算符创建模式验证,以确保totalWithVAT matches the expected combination of price and VAT.totalWithVAT与预期的price和VAT组合匹配。
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)时,才能插入文档。
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 141*(1+0.20)等于169.2,因此totalWithVAT field must be 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
}
}
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.discountedPricemust be less than必须小于lineItems.price.lineItems.price。This rule is specified using the此规则是使用$ltoperator.$lt运算符指定的。Theitemsfield 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要了解有关$exproperator, which allows the use of aggregation expressions within the query language, see$expr.$expr运算符的更多信息,请参阅$expr,该运算符允许在查询语言中使用聚合表达式。