Aggregation Pipeline - Part 1

Learn what an aggregation pipeline is, and practice using operators with the different stages of the aggregation pipelines such as $match and $group.

We'll cover the following

Aggregation fetches data based on the query, processes it, and returns the computed data. It fetches the data at multiple stages, called pipelines. We can use aggregation pipelines to combine results from multiple collections as well. An aggregation pipeline can have more than one stage and every stage performs an operation.

Below is a list of operations we can perform through an aggregation pipeline stage:

  • Filter: A filter operation is performed on a collection through a provided query.
  • Join: Records from different stages can be added to the primary collection records.
  • Group: The results of the previous stage can be grouped.
  • Sort: The results of the previous stage can be sorted.
  • Operations: Counting and merging records, or arithmetic operations.
  • Transforming the output: We can transform a document or decide which fields to return as a result of the aggregation.

The pipeline stages are executed in order and each stage feeds the input for the next stage. The very first stage receives data from the collection and the last stage returns the result. Middle stages can also return query results on a collection. Moreover, they perform other operations on data from previous stages.

Key points:

  • The pipeline stages execute in the order they are provided.
  • To run aggregation, it is not necessary to provide all the stages.
  • There is no fixed order for a stage but for example, performing sort after limit could return the wrong results, so we use the stages accordingly.

Get hands-on with 1200+ tech skills courses.