MongoDB $cond Operator
Photo Credit to CodeToFun
🙋 Introduction
In MongoDB's aggregation framework, the $cond
operator offers a powerful way to perform conditional operations within pipelines. This operator evaluates conditions and returns different results based on whether the conditions are met or not, enabling dynamic data processing and transformation.
Let's delve into the details of how the $cond
operator can be effectively utilized within MongoDB's aggregation pipelines.
💡 Syntax
The syntax for the $cond
method is straightforward:
{ $cond: { if: <condition>, then: <expression>, else: <expression> } }
- $cond: This operator signifies a conditional operation.
- if: This represents the condition to be evaluated.
- then: This specifies the expression to be executed if the condition evaluates to true.
- else: This specifies the expression to be executed if the condition evaluates to false.
📝 Example
⌨️ Input
Consider a collection named students containing documents with fields name, score, and grade. Here are sample documents from the students collection:
[
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "score": 85 },
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "score": 70 },
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "score": 60 }
]
🔄 Aggregation
Suppose we want to categorize students as "Pass" if their score is greater than or equal to 70, and "Fail" otherwise. Here's how you can achieve this using the $cond
operator:
db.students.aggregate([
{
$project: {
name: 1,
grade: {
$cond: {
if: { $gte: ["$score", 70] },
then: "Pass",
else: "Fail"
}
}
}
}
])
🧩 Explanation
- $project: This stage reshapes documents, including only the name field and introducing a new field grade.
- $cond: Evaluates the condition: if the student's score ($score) is greater than or equal to 70, assigns "Pass" to the grade field; otherwise, assigns "Fail".
When discussing how the above aggregation works:
- Alice scored 85, so she gets a "Pass".
- Bob scored exactly 70, which is considered a "Pass".
- Charlie scored 60, which is less than 70, so he gets a "Fail".
💻 Output
Now, let's take a look at the output generated by the aggregation pipeline:
[
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "grade": "Pass" },
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "grade": "Pass" },
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "grade": "Fail" }
]
📚 Use Cases
Conditional Aggregation:
The
$cond
operator is valuable for performing conditional aggregation based on specified criteria.Data Transformation:
Conditional expressions can be used to transform data, categorize records, or derive new fields based on certain conditions.
Dynamic Querying:
In applications where data retrieval depends on specific conditions, the
$cond
operator enables dynamic querying within aggregation pipelines.
🎉 Conclusion
The $cond
operator in MongoDB's aggregation framework provides a flexible and efficient way to incorporate conditional logic into aggregation pipelines. Whether you're categorizing data, deriving new fields, or performing conditional aggregations, mastering the usage of $cond
empowers you to manipulate and transform data dynamically based on specified conditions.
With its intuitive syntax and diverse applications, the $cond
operator proves to be an indispensable asset for handling conditional operations effectively within MongoDB. Incorporate it into your aggregation pipelines to unlock new dimensions of data analysis and gain deeper insights into your datasets.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (MongoDB $cond Operator), please comment here. I will help you immediately.