Aggregation

An analysis and summary of data

Aggregation Pipeline

A series of stages completed one at a time, in order

Structure of an Aggregation Pipeline

db.collection.aggregate([
    {
        $stage1: {
            { expression1 },
            { expression2 }...
        },
        $stage2: {
            { expression1 }...
        }
    }
])

Stage

An aggregation operation performed on the data

$match

The $match stage filters for documents that match specified conditions.

syntax:

{
  $match: {
     "field_name": "value"
  }
}

$group

syntax:

{
  $group:
    {
      _id: <expression>, // Group key
      <field>: { <accumulator> : <expression> }
    }
 }

$sort

The $sort stage sorts all input documents and returns them to the pipeline in sorted order. We use 1 to represent ascending order, and -1 to represent descending order.