Aggregation Reports

Aggregation reports summarize data.

Example questions:

Example: total orders per user

const report = await Order.aggregate([
  { $match: { status: 'paid' } },
  {
    $group: {
      _id: '$userId',
      totalSpent: { $sum: '$amount' },
      orderCount: { $sum: 1 },
    },
  },
  { $sort: { totalSpent: -1 } },
])

Example: monthly revenue

await Order.aggregate([
  { $match: { status: 'paid' } },
  {
    $group: {
      _id: {
        year: { $year: '$createdAt' },
        month: { $month: '$createdAt' },
      },
      revenue: { $sum: '$amount' },
    },
  },
])

What to explain

Interview angle

Explain that aggregation pipelines process documents through stages and are useful for reports, dashboards, and grouped calculations. Put filtering stages early when possible.