Docs Home → Develop Applications → MongoDB Manual
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.例如,如果您有一个依赖于另一个字段的值的字段,并且需要确保这些值彼此正确成比例。
You can't specify the following query operators in a 不能在验证器对象中指定以下查询运算符:validator object:
You can't specify schema validation for:不能为以下项指定架构验证:
Collections in the admin, local, and config databasesadmin、local和config数据库中的集合
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
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 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)时,才能插入文档。
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 } }
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")
}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.price。This rule is specified using the 此规则使用$lt operator.$lt运算符指定。
The items field must be an array. items字段必须是数组。This rule is specified using 此规则使用$jsonSchema$jsonSchema指定
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