MongoDB is a powerful NoSQL database that allows developers to store and query data in a flexible and efficient manner. One of the most useful operators in MongoDB’s aggregation framework is the $cond operator. This operator lets you add conditional logic to your aggregation pipelines, making it incredibly versatile when working with complex queries.
What is the $cond Operator?
The $cond operator is MongoDB’s way of allowing conditional logic within aggregation queries, similar to an if-else statement in traditional programming languages. It evaluates a condition and returns a value based on whether the condition is true or false. This is particularly useful when you need to make decisions about your data based on specific criteria.
Syntax
The $cond operator follows this syntax:
{
$cond: [
<condition>, // The condition to evaluate (true or false)
<ifTrue>, // Value to return if condition is true
<ifFalse> // Value to return if condition is false
]
}
-
condition: A Boolean expression to evaluate. -
ifTrue: The value to return if the condition evaluates totrue. -
ifFalse: The value to return if the condition evaluates tofalse.
Simple Example: Using $cond in Aggregation
Suppose you have a collection of products with fields like price and category. You want to calculate a discount on the products based on their category:
{
"_id": 1,
"name": "Laptop",
"price": 1000,
"category": "Electronics"
}
You can use the $cond operator in an aggregation pipeline to apply a discount based on the category:
db.products.aggregate([
{
$project: {
name: 1,
price: 1,
discountedPrice: {
$cond: {
if: { $eq: ["$category", "Electronics"] },
then: { $multiply: ["$price", 0.9] }, // Apply 10% discount
else: "$price" // No discount for other categories
}
}
}
}
]);
In this example:
-
If the
categoryis"Electronics", thediscountedPricewill be 10% less than the original price. -
If the category is not
"Electronics", the originalpriceis used as thediscountedPrice.
Advanced Example: Using $cond with Multiple Conditions
The $cond operator can also be nested for more complex logic. For example, suppose you want to categorize products as “Cheap”, “Moderate”, and “Expensive” based on their price:
db.products.aggregate([
{
$project: {
name: 1,
price: 1,
priceCategory: {
$cond: {
if: { $lt: ["$price", 500] },
then: "Cheap",
else: {
$cond: {
if: { $lt: ["$price", 1000] },
then: "Moderate",
else: "Expensive"
}
}
}
}
}
}
]);
In this example:
-
If the price is less than
500, thepriceCategorywill be"Cheap". -
If the price is between
500and1000, it will be"Moderate". -
If the price is greater than
1000, it will be"Expensive".
This demonstrates how the $cond operator can handle multiple conditions and provide a branching logic mechanism.
Real-World Use Cases for $cond
-
Data Transformation: Often, you may need to transform or categorize your data based on certain conditions. The
$condoperator allows you to do this in one step without having to post-process the data in your application code. -
Conditional Aggregation: You can use
$condto create conditional aggregations, such as applying different discounts, tax rates, or shipping fees based on user roles, item categories, or other criteria. -
Complex Logic in Pipelines: The
$condoperator is a powerful tool to implement business rules directly in your database query, making your pipelines more flexible and reducing the amount of logic required in your application code.
Conclusion
The $cond operator is an incredibly useful tool in MongoDB for adding conditional logic to your aggregation pipelines. Whether you need to apply different transformations based on field values or implement complex decision trees, $cond makes it easy to handle such conditions directly within your queries. By using $cond, you can reduce post-processing in your application code and streamline your data transformations, leading to more efficient and scalable MongoDB queries.