Thuta Learning
AdvancedData & Databasesintermediate

MongoDB aggregate() and Aggregation Pipeline

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Build an aggregation pipeline
  • Understand stage ordering
  • Use group accumulators

Let's break it down simply

In an aggregation pipeline, documents pass through each stage in order. Putting $match early trims the data down before $group does its counting and grouping. aggregate() doesn't touch the underlying collection data unless $out or $merge is used.

javascript
db.orders.aggregate([
  { $match: { status: 'paid' } },
  {
    $group: {
      _id: '$customerId',
      orderCount: { $sum: 1 },
      totalSpent: { $sum: '$total' }
    }
  },
  { $match: { totalSpent: { $gte: 100000 } } },
  { $sort: { totalSpent: -1 } },
  { $project: { _id: 0, customerId: '$_id', orderCount: 1, totalSpent: 1 } }
])
You should see
{ customerId: 42, orderCount: 3, totalSpent: 185000 }

Try it yourself

Group the products collection by category and calculate the average price and product count.

Aggregation PipelineMongoDB

Easy traps

  • Doing all your filtering only after $group, forcing far more documents than necessary to pass through the pipeline
  • Forgetting to put a $ in front of a field path

Exercise

Group the products collection by category and calculate the average price and product count.

You'll know it worked when: { customerId: 42, orderCount: 3, totalSpent: 185000 }

MongoDB aggregate() and Aggregation Pipeline | Thuta Learning