Aggregation Pipeline

Process data through a sequence of stages. Each stage transforms the document stream.

Stages

StageDescription
$matchFilter documents using query operators
$groupGroup by key with accumulators ($sum, $avg, $min, $max, $count, $first, $last, $push)
$sortSort documents (1 asc, -1 desc)
$projectInclude/exclude fields, compute new fields
$limitLimit output count
$skipSkip N documents
$unwindDeconstruct array field into separate documents
$addFieldsAdd computed fields
$lookupJoin with another collection
$countCount documents and output as named field

Group Accumulators

[
  {"$group": {
    "_id": "$department",
    "avg_salary": {"$avg": "$salary"},
    "total": {"$sum": 1},
    "max_age": {"$max": "$age"},
    "names": {"$push": "$name"}
  }},
  {"$sort": {"avg_salary": -1}},
  {"$limit": 5}
]

$lookup (Join)

{
  "$lookup": {
    "from": "orders",
    "local_field": "_id",
    "foreign_field": "user_id",
    "as": "user_orders"
  }
}

Expression Operators

Use inside $project and $addFields:

{"$addFields": {
  "total": {"$add": ["$price", "$tax"]},
  "discount_price": {"$multiply": ["$price", 0.9]}
}}

Available: $add, $subtract, $multiply, $divide