Complex Expressions
- $expr operator allows us to perform aggregation expressions within a query.
- It is useful when we need to compare fields from the same document in a more complex manner.
shop> db.products.find({$expr: {$gt: ['$price', 1340]}})
- Find sales whose quantity * price is greater than the target price.
shop> db.sales.find({$expr: {$gt: [{$multiply: ['$quantity', '$price']}, '$targetPrice']}})
[
{ _id: 1, quantity: 10, price: 15, targetPrice: 120 },
{ _id: 5, quantity: 5, price: 55, targetPrice: 150 },
{ _id: 4, quantity: 5, price: 55, targetPrice: 150 },
{ _id: 3, quantity: 6, price: 35, targetPrice: 100 },
{ _id: 2, quantity: 5, price: 25, targetPrice: 100 }
]
- Find sales whose quantity + price is less than the target price.
shop> db.sales.find({$expr: {$lt: [{$add: ['$quantity', '$price']}, '$targetPrice']}})
[
{ _id: 1, quantity: 10, price: 15, targetPrice: 120 },
{ _id: 5, quantity: 5, price: 55, targetPrice: 150 },
{ _id: 4, quantity: 5, price: 55, targetPrice: 150 },
{ _id: 3, quantity: 6, price: 35, targetPrice: 100 },
{ _id: 2, quantity: 5, price: 25, targetPrice: 100 }
]