MongoDB Aggregation Pipeline - $function Stage
Tags: webdev, javascript, mongodb, productivity
Published: 2023-02-05 18:45:48

### An Overview

A popular NoSQL database called MongoDB offers a scalable and adaptable option for storing and handling enormous amounts of data. The aggregation pipeline, which enables users to carry out complex data analysis and manipulation, is one of MongoDB's core features. The `$function` stage of the MongoDB aggregation pipeline and its use cases will be the main topic of this blog.

---

### What is the $function Stage in MongoDB Aggregation Pipeline?

The MongoDB aggregation pipeline has an additional stage called `$function` that enables users to write their own unique JavaScript functions for data processing. When there is no built-in stage that can carry out the needed operation, this stage is especially helpful. Users have access to the complete JavaScript runtime and the MongoDB aggregation framework because the $function stage is executed within the context of the MongoDB server.

---

### Syntax:

The following syntax is used to define the `$function` stage:

```
{
  $function: {
    body: <code>,
    args: <array expression>,
    lang: "js"
  }
}
```

The `args` field specifies an optional initial value that will be provided to the function, and the `body` field specifies the JavaScript function definition that will be performed. You can specify an empty array []. If the body function does not accept an argument. lang is The language used in the body need to specify `lang: "js"`.

---

### Use Cases for the `$function` Stage in MongoDB Aggregation Pipeline


1. **Running totals computation**: The `$function` stage can compute running totals by storing the cumulative sum in the state object.

2. **Implement custom algorithms**: Custom algorithms that cannot be implemented with the built-in stages can be implemented using the `$function` stage.

3. **Transforming Array**: Arrays can be transformed by mapping, filtering, or reducing the items of the array using the `$function` stage.

---

### Example:

Consider the following input document in the "`customer`" collection:


```
{
  "_id": 1,
  "name": "Shubham Dutta",
  "email": "shubham_dutta@gmail.com",
  "position": "Developer"
},

{
  "_id": 2,
  "name": "Arjun Dutta",
  "email": "arjun.dutta@gmail.com",
  "position": "Designer"
}
```

Now, we need to separate out each customer's first name from their entire name and lowercase the position. The aggregate process listed below can be used to do this:

```
db.customers.aggregate([
  {
    $project: {
      'name': {
        $function: {
          body: function (name) {
            let firstName = name.split(" ")[0];
            return firstName;
          },
          args: {"$name"},
          lang: "js",
        },
      },
      'position': {
        $function: {
          body: function (position) {
            let position = position.toLowerCase();
            return position;
          },
          args: {"$position"},
          lang: "js",
        },
      },
    },
    '_id': 0,
    'email': 1
  },
]);
```

The following is the result of the above pipeline:

```
[
  {
    "name": "Shubham",
    "email": "shubham_dutta@gmail.com",
    "position": "Developer"
  },
  {
    "name": "Arjun",
    "email": "arjun.dutta@gmail.com",
    "position": "designer"
  }
]
```

By splitting the name field on the space character and returning the first element of the resulting array, the first name of each customer is extracted from their entire name  using the `$function` stage in this example. The toLowerCase() method is used to change the position field's case to lowercase. Each customer's name, email address, and position are included in a new object that is returned by the function argument using $project.

---

### Conclusion

The MongoDB aggregation pipeline has a significant feature called the `$function` stage that enables users to write unique JavaScript functions for data processing. 

The `$function` stage gives you the freedom and power you need to design custom algorithms, manipulate arrays, or compute running totals. 

You can fully utilize this feature and unleash the complete power of your MongoDB data by understanding the syntax and application of the `$function` stage.