Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

MongoDB Aggregation

MongoDB $cond Operator

Updated on Oct 30, 2024
By Mari Selvan
👁️ 36 - Views
⏳ 4 mins
💬 1 Comment
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:

syntax.js
Copied
Copy To Clipboard
{ $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:

Input
Copied
Copy To Clipboard
[
  { "_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:

example.js
Copied
Copy To Clipboard
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:

Output
Copied
Copy To Clipboard
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "grade": "Pass" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "grade": "Pass" },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "grade": "Fail" }
]

📚 Use Cases

  1. Conditional Aggregation:

    The $cond operator is valuable for performing conditional aggregation based on specified criteria.

  2. Data Transformation:

    Conditional expressions can be used to transform data, categorize records, or derive new fields based on certain conditions.

  3. 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:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

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

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy