> For the complete documentation index, see [llms.txt](https://anon-coders-notes.gitbook.io/techwriterdev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anon-coders-notes.gitbook.io/techwriterdev/database/nosql/mongodb/09_aggregationframework_001.md).

# MongoDB Aggregation Framework

* Aggregation framework is just another way of querying data in mongodb.
* It enables you to group data, perform calculations, reshape data etc.
* It works based on the concept called, pipeline. Pipeline consists of,
  * Composition of stages.
  * Configurable transformation.
  * Stages can be arranged in multiple ways *(with few eceptions)*.
* Pipeline are always an array of operations of one or more stages.
* Stages are composed of one or more aggregation operators or expressions.
  * The expression may take single or an array of arguments i.e expression dependent.
* Syntax

  ```
      db.collection_name.aggregate([{stage1},{stage2},...,{stageN}], {options})
  ```
* Example

  ```
        db.accounts.aggregate([
            {
                "$match": {"amenities":"Wifi"}
            }
            { 
                "$project": {"price": 1, "name": "Joe", "_id":0 }
            }
        ])
    
  ```

  * In the above example, we prepare an aggregation pipeline when we use **aggregate** function.
  * The first aggregation operator in pipeline is "$match" operation **and** then "$project" agggegation operation.
  * The aggregate function takes **array** as parameter. This array represents order of aggregation operation in pipeline as per which data need to be modified or organized.
  * The above query helps in **filtering** documents based on the match of field value and then only **projecting** based on field specified.

![Aggregation Pipeline](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-bd8f54be624f462843d467c11b51d7699db0df86%2FMongodb_Aggregate_Pipeline.png?alt=media)

* MQL can be considered as a subset of aggregation. ![Aggregation vs MQL](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-02a0d767c9a566497da5a4fea2da518c0db15d3c%2FAggregation_wrt_MQL.png?alt=media)
  * Read more about it [here](https://www.mongodb.com/developer/how-to/SQL-to-Aggregation-Pipeline/).

## Some aggregation terms

* **Field Path**
  * Example
    * `"$fieldName"`
* **System Variable**
  * Example
    * `"$$CURRENT"`
      * All uppercase variables are system variable.
* **User Variable**
  * Example
    * `"$$foo"`
      * All lowercase variables are user variable.
