> This page location: /docs.md > /docs/development.md > /docs/charts.md > /docs/charts/build-charts.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Backing Aggregation Pipeline

To get the data needed to render a chart, Charts creates a MongoDB Aggregation Pipeline and runs the pipeline on the MongoDB database server. The pipeline consists of multiple stages, each of which is generated based on different settings specified by the chart's author.

This document explains how the various Chart Builder settings are used to construct the Aggregation Pipeline. You can view the pipeline used to create a chart by choosing the View Aggregation Pipeline option in the Chart Builder's ellipsis dropdown on the top right.

Atlas Charts construct a pipeline that consists of the following segments in the following order:

1. [Charts views](https://www.mongodb.com/docs/charts/create-manage-charts-view.md#std-label-data-sources-pipeline)

2. [Pre-filters in embedding charts](https://www.mongodb.com/docs/charts/filter-embedded-charts.md#std-label-embed-options-pre-filter)

3. [Dashboard filters](https://www.mongodb.com/docs/charts/dashboards/view-dashboard-data/dashboard-filtering.md#std-label-filter-dashboards)

4. [Chart query](https://www.mongodb.com/docs/charts/filter-chart-results.md#std-label-query-bar)

5. [Lookup fields](https://www.mongodb.com/docs/charts/add-lookup-field.md#std-label-add-lookup-field)

6. [Calculated fields](https://www.mongodb.com/docs/charts/calculated-fields.md#std-label-calculated-fields)

7. [Embedding filters, including injected filters](https://www.mongodb.com/docs/charts/embedded-chart-options.md)

8. [Chart filters](https://www.mongodb.com/docs/charts/filter-chart-results.md#std-label-charts-filter-documents)

9. [Encoded fields](https://www.mongodb.com/docs/charts/encoding-channels.md#std-label-encoding-channels)

10. [Sorting](https://www.mongodb.com/docs/charts/bin-data.md#std-label-charts-sort-data)

11. [Maximum document limit](https://www.mongodb.com/docs/charts/chart-types.md#std-label-max-documents-limit)

**Note:**

When creating a chart, you can configure some but not all of the previous chart segments. When Charts generates the aggregation pipeline, it skips unspecified segments.

## Example

The following chart shows the total sale amounts from an office supply company, categorized by purchase method. Each document in the data collection represents a single sale.

Using this chart as an example, we will explore how the specifications for each of the above settings change the aggregation pipeline generated by Atlas Charts.

![Aggregation pipline example without any filters.](/images/charts/agg-pipeline.png)

### Encoding

Without any Data Source pipeline, Query bar queries, calculated fields, and filters added in the Filter pane, Atlas Charts generates the following aggregation pipeline:

```javascript
{
  "$addFields": {              // Encoding
    "__alias_0": {
      "$sum": "$items.price"
    }
  }
},
{
  "$group": {
    "_id": {
      "__alias_1": "$purchaseMethod"
    },
    "__alias_0": {
      "$sum": "$__alias_0"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "__alias_1": "$_id.__alias_1",
    "__alias_0": 1
  }
},
{
  "$project": {
    "x": "$__alias_1",
    "y": "$__alias_0",
    "_id": 0
  }
},

{
  "$addFields": {              // Sorting
    "__agg_sum": {
      "$sum": [
        "$y"
      ]
    }
  }
},
{
  "$sort": {
    "__agg_sum": -1
  }
},
{
  "$project": {
    "__agg_sum": 0
  }
},
{
  "$limit": 5000
}
```

The pipeline at this point consists of groups from the Encode panel, stages for the default sort order, and the maximum document limit, which is set to 5000 by Atlas Charts.

### Adding Queries

The query below restricts the documents shown to only those with a `saleDate` equal to or more recent than `January 1, 2017` with at least 5 elements in the `items` array. `items` is an array where each element is an item purchased during a sale.

Query:

```javascript
{
  $and: [
  {
    saleDate: { $gte: new Date("2017-01-01") }
  },
  {
    'items.4': { $exists: true }
  } ]
}
```

Applying the above query in the Query bar generates the following chart and aggregation pipeline:

![Aggregation pipline example with query.](/images/charts/agg-pipeline-query.png)

Aggregation Pipeline:

```javascript
{
  "$match": {              // Query
    "$and": [
      {
        "saleDate": {
          "$gte": {
            "$date": "2017-01-01T00:00:00Z"
          }
        }
      },
      {
        "items.4": {
          "$exists": true
        }
      }
    ]
  }
},
{
  "$addFields": {
    "__alias_0": {
      "$sum": "$items.price"
    }
  }
},
{
  "$group": {
    "_id": {
      "__alias_1": "$purchaseMethod"
    },
    "__alias_0": {
      "$sum": "$__alias_0"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "__alias_1": "$_id.__alias_1",
    "__alias_0": 1
  }
},
{
  "$project": {
    "x": "$__alias_1",
    "y": "$__alias_0",
    "_id": 0
  }
},
{
  "$addFields": {
    "__agg_sum": {
      "$sum": [
        "$y"
      ]
    }
  }
},
{
  "$sort": {
    "__agg_sum": -1
  }
},
{
  "$project": {
    "__agg_sum": 0
  }
},
{
  "$limit": 5000
}
```

The aggregation pipeline now starts with the query applied, and is followed by the groups selected in the Encode panel and the max document limit.

### Adding Calculated Fields

We can also change the chart to show the total revenue generated categorized by purchase method. To accomplish this task, we will create a calculated field that calculates the total revenue by multiplying price by quantity. Adding this new calculated field, in addition to the query above, produces the following chart and pipeline:

Calculated Field Expression:

![Aggregation pipline example with calculated field.](/images/charts/agg-pipeline-calc-field.png)

Aggregation Pipeline:

```javascript
{
  "$match": {
    "$and": [
      {
        "saleDate": {
          "$gte": {
            "$date": "2017-01-01T00:00:00Z"
          }
        }
      },
      {
        "items.4": {
          "$exists": true
        }
      }
    ]
  }
},
{
  "$addFields": {              // Calculated Field
    "revenue": {
      "$reduce": {
        "input": "$items",
        "initialValue": 0,
        "in": {
          "$sum": [
            "$$value",
            {
              "$multiply": [
                "$$this.price",
                "$$this.quantity"
              ]
            }
          ]
        }
      }
    }
  }
},
{
  "$group": {
    "_id": {
      "__alias_0": "$purchaseMethod"
    },
    "__alias_1": {
      "$sum": "$revenue"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "__alias_0": "$_id.__alias_0",
    "__alias_1": 1
  }
},
{
  "$project": {
    "x": "$__alias_0",
    "y": "$__alias_1",
    "_id": 0
  }
},
{
  "$addFields": {
    "__agg_sum": {
      "$sum": [
        "$y"
      ]
    }
  }
},
{
  "$sort": {
    "__agg_sum": -1
  }
},
{
  "$project": {
    "__agg_sum": 0
  }
},
{
  "$limit": 5000
}
```

The updated pipeline now includes the calculated field right below the query applied in the Query bar while the order of the rest of the components remains unchanged.

### Adding Filters

This chart can be further refined by adding a filter in the Filter pane to only select in-store sales made in the New York location. Adding this filter produces the following chart and aggregation pipeline:

![Aggregation pipline example with filter.](/images/charts/agg-pipeline-with-filter.png)

Aggregation Pipeline:

```javascript
{
  "$match": {
    "$and": [
      {
        "saleDate": {
          "$gte": {
            "$date": "2017-01-01T00:00:00Z"
          }
        }
      },
      {
        "items.4": {
          "$exists": true
        }
      }
    ]
  }
},
{
  "$addFields": {
    "revenue": {
      "$reduce": {
        "input": "$items",
        "initialValue": 0,
        "in": {
          "$sum": [
            "$$value",
            {
              "$multiply": [
                "$$this.price",
                "$$this.quantity"
              ]
            }
          ]
        }
      }
    }
  }
},
{
  "$match": {             // Filter
    "storeLocation": {
      "$in": [
        "New York"
      ]
    }
  }
},
{
  "$group": {
    "_id": {
      "__alias_0": "$purchaseMethod"
    },
    "__alias_1": {
      "$sum": "$revenue"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "__alias_0": "$_id.__alias_0",
    "__alias_1": 1
  }
},
{
  "$project": {
    "x": "$__alias_0",
    "y": "$__alias_1",
    "_id": 0
  }
},
{
  "$addFields": {
    "__agg_sum": {
      "$sum": [
        "$y"
      ]
    }
  }
},
{
  "$sort": {
    "__agg_sum": -1
  }
},
{
  "$project": {
    "__agg_sum": 0
  }
},
{
  "$limit": 5000
}
```

The pipeline now includes the `storeLocation` filter right below the calculated field while the order of the rest of the components remains unchanged.
