The ‘$expr‘ operator is used in MongoDB to perform complex queries using aggregation expressions. With this operator, you can use any aggregation expression in the query, including arithmetic operations, boolean logic, and string manipulation. The main benefits of using ‘$expr‘ operator are that it allows you to filter documents based on complex criteria that cannot be expressed in a simple query and it runs using the aggregation pipeline, which provides a flexible and powerful way to query MongoDB.
Let us consider an example to understand how we can use the ‘$expr‘ operator. Suppose we have a collection ‘sales‘ that contains documents with the following fields: ‘product‘, ‘quantity‘, and ‘price‘. We want to find all products that have sold for a total revenue of more than $1000. We can use the following aggregation query with the ‘$expr‘ operator to achieve this:
db.sales.aggregate([
{
$group: {
_id: "$product",
totalRevenue: { $sum: { $multiply: [ "$quantity", "$price" ] } }
}
},
{
$match: {
$expr: { $gt: [ "$totalRevenue", 1000 ] }
}
}
])
In this query, we first group the documents by ‘product‘ and calculate the total revenue for each product using the ‘$sum‘ and ‘$multiply‘ operators in the projection stage. Then we use the ‘$expr‘ operator to match only those documents where the calculated ‘totalRevenue‘ is greater than ‘1000‘.
The ‘$expr‘ operator can also be used to perform more complex queries using other aggregation expressions. For example, suppose we want to find all documents in a collection ‘orders‘ where the quantity is less than the average quantity for all orders. We can use the following aggregation query with the ‘$expr‘ operator to achieve this:
db.orders.aggregate([
{
$group: {
_id: null,
avgQuantity: { $avg: "$quantity" }
}
},
{
$match: {
$expr: { $gt: [ "$quantity", "$avgQuantity" ] }
}
}
])
In this query, we first use the ‘$avg‘ operator to calculate the average quantity for all orders. Then we use the ‘$expr‘ operator to match only those documents where the ‘quantity‘ is greater than the ‘avgQuantity‘ calculated in the previous stage.
In conclusion, the ‘$expr‘ operator in MongoDB is a powerful tool that allows you to filter documents based on complex criteria using aggregation expressions. By using the ‘$expr‘ operator in the aggregation pipeline, you can easily perform complex queries that cannot be expressed in a simple query.