Sikau

MongoDB · Day 11 · about 35 min

The aggregation pipeline

$match, $group, $sort and $project.

An assembly line for data

Reports need grouping, totals and reshaping. The aggregation pipeline passes documents through stages, each transforming the output of the last: filter → group → sort → reshape. It's MongoDB's answer to SQL's GROUP BY and much more.

Stages

printjson(db.dishes.aggregate([
  { $match: { price: { $gte: 100 } } },
  { $group: { _id: "$category", dishes: { $sum: 1 }, avgPrice: { $avg: "$price" }, names: { $push: "$name" } } },
  { $sort: { avgPrice: -1 } },
  { $project: { _id: 0, category: "$_id", dishes: 1, avgPrice: { $round: ["$avgPrice", 0] }, names: 1 } },
]));
  • { $sum: 1 } counts documents; { $sum: "$price" } adds a field.
  • _id: null groups everything into one result.
  • $count, $limit, $skip, $addFields and $sortByCount are handy shortcuts.

The rest of this lesson

  • Building a pipeline step by stepexplain
  • Expressions inside stagesexplain
  • How many results?predict
  • Pipeline orderorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB