MongoDB Aggregation In-Depth: Array, Conditional, and Dynamic Operations
Tags: webdev, mongodb, dbms, computerscience
Published: 2023-11-09 12:46:47


![MongoDB Karan Chugh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y263fkwo5vi4lfk2ei8q.png)

Building on the solid foundation laid in our previous exploration of MongoDB Aggregation basics, we're diving even deeper into the toolbox of aggregation operators. In this part, we'll unravel the versatility of array operations, set manipulations, and dynamic expressions—unleashing the true potential of MongoDB Aggregation for your data. If you haven't caught up on the fundamentals, make sure to check out my first article [here](https://dev.to/karanchugh02/mongodb-aggregation-in-depth-fundamentals-and-pipeline-mastery-fig) for a seamless learning journey.


###Array Operators

Arrays in MongoDB are powerful data structures, and with the introduction of array operators in the Aggregation Framework, we unlock a whole new dimension of possibilities. These operators allow us to dynamically manipulate and reshape arrays within our documents, paving the way for more complex data analyses. In this section, we'll explore key array operators—each with its unique role in enhancing our ability to work with arrays seamlessly. Let's dive in! 🚀📊

***_$unwind_*** :- The $unwind operator in Aggregation is like unfolding a packed suitcase—it takes an array field and unpacks it, revealing each item as its own document. Imagine a student document with subjects in an array. applying $unwind transforms it into separate documents for each subject. For instance:

Raw structure of a student in collection
```
{
  "student_id": 1,
  "name": "Rahul",
  "score" : 75,
  "subjects": ["Math", "Physics", "Chemistry"]
}
```

Impact after $unwind on subjects field
```
[
{
  "student_id": 1,
  "name": "Rahul",
  "subject": "Math"
},
{
  "student_id": 1,
  "name": "Rahul",
  "subject": "Physics"
},
{
  "student_id": 1,
  "name": "Rahul",
  "subject": "Chemistry"
}
]
```

Aggregation pipeline for $unwind
```
[
  {
    $unwind: "$subjects"
  }
]
```

This operation allows for more detailed analysis of individual elements within an array. 

***_$push_*** :- The $push operator is a tool for appending elements to an array. This is mainly used in update and upsert operations rather than aggregation. Let's suppose we have a subjects array in student document and we want to add a new subject to that student, So we'll use $push in this case to append new subject in subjects array.

```
db.students.updateOne(
   { _id: 1 },
   { $push: { subjects:'Math' } }
)
```

***_$addToSet_*** :- The purpose of the $addToSet operator is evident from its name. Its functionality is akin to that of $push, with the added assurance that the array into which elements are being pushed remains unique after each insertion. This operator ensures the continual uniqueness of the array, preventing the inclusion of duplicate elements.

```
db.students.updateOne(
   { _id: 1 },
   { $addToSet: { subjects:'Math' } }
)
```

###Conditional Operators

***_$cond_*** :- The $cond operator is similar to an intelligent decision-maker in the world of MongoDB Aggregation. It allows us to implement conditional expressions, making our aggregations dynamic and responsive to varying criteria.

Example:
consider a scenario where we need to return a key in result whether the student is pass or fail based upon the score, this is the case where we'll use $project with $cond and return a new key in each object which will contain the information regarding the result of student.

```
[
  {
    $project: {
      first_name : 1,
      marks : 1,
      result : {
        $cond :{
          if : {$gte : ["$marks" , 35]},
          then : "Pass",
          else : "Fail"
        }
      }
    }
  }
]
```


![MongoDB Karan Chugh](https://imgix.cosmicjs.com/a073df30-7edb-11ee-955f-5fd6e82e9841-cond.png)

***_$switch_*** :- The $switch operator in MongoDB Aggregation takes decision-making to the next level by executing switch-case statements within the aggregation pipeline. This versatile operator allows us to evaluate multiple conditions and choose the appropriate outcome.

Let's say we want to assign letter grades to students based on their exam scores:

```
[
  {
   $project: {
    "first_name": 1,
    "grade": {
      $switch: {
        branches: [
          { case: { $gte: ["$marks", 90] }, then: "A" },
          { case: { $gte: ["$marks", 80] }, then: "B" },
          { case: { $gte: ["$marks", 70] }, then: "C" },
          { case: { $gte: ["$marks", 60] }, then: "D" },
          { case: true, then: "F" }
        ]
      }
    }
  }
 }
]

```
![MongoDB Karan Chugh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xu806pge35qbl0ayh74e.png)

###Dynamic Operators

Now, let's take a stroll into the dynamic side of MongoDB Aggregation—where things get flexible and responsive. This includes operators like $map and $filter which are the backbone of pipeline while performing operations on array fields. 

***_$map_*** :-
The $map operator—a dynamic tool in MongoDB Aggregation that crafts transformations with finesse.
For instance, we have an array of marks and we need to return the response in a way where each element in marks is increased by 5. In that case where we can clearly see that we'll need to iterate over the array and perform any kind of operation, $map is used.

```
[
  {
    $project: {
      name : 1,
      marks : 1,
      newMarks: {
        $map :{
          input : "$marks",
          as : "rawMarks",
          in : {$add : ['$$rawMarks', 5]}
          
        }
      }
    }
  }
]
```

![MongoDB Karan Chugh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xhwpqqg32vb61mpdy34.png)


***_$filter_*** :-
$filter dynamically selects elements from an array based on specified conditions. It is useful when we need to retrieve specific elements based on some criteria.

Handling a case where we need to filter the marks array based on a criteria that each element should be greater than a particular value.

```
[
  {
    $project: {
      name : 1,
      marks : 1,
      newMarks: {
        $filter :{
          input : "$marks",
          as : "score",
          cond : {$gte : ['$$score', 60]}
        }
      }
    }
  }
]
```


![MongoDB Karan Chugh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozgb2b4awx3tx5j4msf4.png)



###Wrap Up
In wrapping up our exploration of dynamic operators in MongoDB Aggregation, we've witnessed the prowess of $map in crafting dynamic transformations and $filter in dynamically sifting through arrays. These operators bring a layer of adaptability and finesse to our data manipulations, opening doors to creative and tailored aggregations.

***What's Next?***

Our journey doesn't end here! In the upcoming article, we'll delve into the realm of table joins using the powerful $lookup operator. Get ready to connect the dots across collections for a holistic view of your data. Additionally, we'll demystify pagination controls and sorting, providing you with the tools to navigate and organize your aggregated results effortlessly.

***Stay Connected:***

For more insights and updates, follow me on [LinkedIn](https://www.linkedin.com/in/karan-chugh-953500204/). Join the conversation, share your thoughts, and let's continue this exciting exploration of MongoDB Aggregation together!

Stay curious, stay dynamic! 🚀💻