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限制
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. 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: 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
}
}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.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 Predicates.要查看MongoDB中可用的所有查询运算符,请参阅查询谓词。To learn more about the要了解有关$exproperator, which allows the use of aggregation expressions within the query language, see$expr.$expr运算符的更多信息,该运算符允许在查询语言中使用聚合表达式,请参阅$expr。