knaxuslearn · build · ship

Projects / Product catalog / Phase 4

Phase 4 of 4 · about 2.5 hours

A sales report with an aggregation pipeline

You end with a revenue report that you checked three different ways, and it matches every time.

A shop also has orders. An order holds a list of items, each with a sku, a quantity and the price paid at that moment. We copy the price into the order on purpose: if the product's price changes next week, last week's order must not change with it.

Step 4.1: Twenty thousand orders (about 25 minutes)

This script reads every product's price into memory, then builds 20,000 orders with one to four items each. About one order in twenty is refunded. The generator is seeded, so the data is the same every time.

const prices = new Map(
  (await db.products.find({}, { _id: 0, sku: 1, price_cents: 1 }).toArray()).map((p) => [
    p.sku,
    p.price_cents,
  ]),
);

let state = 7;
const roll = (low, high) => low + ((state = (state * 48271) % 2147483647) % (high - low + 1));

const orders = [];
for (let orderNo = 1; orderNo <= 20000; orderNo++) {
  const items = [];
  const lines = roll(1, 4);
  for (let line = 0; line < lines; line++) {
    const sku = 'P-' + String(roll(1, 200000)).padStart(6, '0');
    items.push({ sku, qty: roll(1, 3), price_cents: prices.get(sku) });
  }
  orders.push({
    order_no: orderNo,
    customer: roll(1, 2000),
    status: roll(1, 20) === 1 ? 'refunded' : 'paid',
    created_at: new Date(Date.UTC(2025, 0, 1) + roll(0, 364) * 86400000),
    items,
  });
}

await db.orders.insertMany(orders);
console.log({
  orders: await db.orders.countDocuments(),
  refunded: await db.orders.countDocuments({ status: 'refunded' }),
});

Step 4.2: Your first pipeline (about 40 minutes)

An aggregation pipeline is a list of stages, and each stage takes the documents from the one before it and passes new ones on. Here is a question: which five products earned the most money from paid orders?

db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $unwind: '$items' },
  {
    $group: {
      _id: '$items.sku',
      units: { $sum: '$items.qty' },
      revenue_cents: { $sum: { $multiply: ['$items.qty', '$items.price_cents'] } },
    },
  },
  { $sort: { revenue_cents: -1, _id: 1 } },
  { $limit: 5 },
]);

Read the stages in order. $match keeps paid orders only. $unwind turns an order with three items into three documents, one per item, so each item can be counted by itself. $group collects them by sku and adds up units and revenue; $multiply makes the line total from quantity and price. $sort puts the biggest first, with the sku as a tiebreaker so the answer is always the same. $limit keeps five.

Each stage hands its documents to the next.

Step 4.3: Join the product, group by category (about 35 minutes)

Orders know skus, not categories. $lookup joins another collection: for every sku it finds the product with that sku and attaches it. Then we group again, this time by the product's category. We store the pipeline in a variable because we will reuse it:

const revenueByCategory = [
  { $match: { status: 'paid' } },
  { $unwind: '$items' },
  {
    $group: {
      _id: '$items.sku',
      revenue_cents: { $sum: { $multiply: ['$items.qty', '$items.price_cents'] } },
    },
  },
  { $lookup: { from: 'products', localField: '_id', foreignField: 'sku', as: 'product' } },
  { $unwind: '$product' },
  { $group: { _id: '$product.category', revenue_cents: { $sum: '$revenue_cents' } } },
  { $sort: { revenue_cents: -1 } },
];

db.orders.aggregate(revenueByCategory);

The $lookup is fast because sku has the unique index we made in Phase 1. Without it, MongoDB would scan the products collection once for every sku.

Step 4.4: Revenue by month (about 20 minutes)

The same shape of pipeline answers a question about time. $dateToString turns a date into text such as 2025-03, and we group by that:

const revenueByMonth = [
  { $match: { status: 'paid' } },
  { $unwind: '$items' },
  {
    $group: {
      _id: { $dateToString: { format: '%Y-%m', date: '$created_at' } },
      units: { $sum: '$items.qty' },
      revenue_cents: { $sum: { $multiply: ['$items.qty', '$items.price_cents'] } },
    },
  },
  { $sort: { _id: 1 } },
];

db.orders.aggregate(revenueByMonth);

Step 4.5: Put the filter first, and give it an index (about 25 minutes)

Pipelines run in order, so the first $match decides how many documents travel through the rest. A $match at the very start can also use an index, the same way a find does. The plan helper from Step 3.2 shows it, using a find with the same filter as a pipeline's $match would use. First, without an index that fits:

const march = {
  status: 'paid',
  created_at: { $gte: ISODate('2025-03-01'), $lt: ISODate('2025-04-01') },
};
await plan(db.orders.find(march));

Then with a compound index on status and created_at:

db.orders.createIndex({ status: 1, created_at: 1 });
await plan(db.orders.find(march));

The same rule as before holds: equality field first, range field second. Put a $match at the start of a pipeline whenever you can, and give it an index.

Step 4.6: Check the report three ways (about 25 minutes)

A report is only useful if it is right. We have computed the total revenue of paid orders in two pipelines, one grouped by category and one by month. Now we add a third, independent way: a plain loop in JavaScript that reads every paid order and adds up quantity times price. All three must agree.

const sumRevenue = (rows) => rows.reduce((total, row) => total + row.revenue_cents, 0);

const byCategory = await db.orders.aggregate(revenueByCategory).toArray();
const byMonth = await db.orders.aggregate(revenueByMonth).toArray();

let byLoop = 0;
for await (const order of db.orders.find({ status: 'paid' })) {
  for (const item of order.items) byLoop += item.qty * item.price_cents;
}

console.log({
  by_category: sumRevenue(byCategory),
  by_month: sumRevenue(byMonth),
  by_loop: byLoop,
  all_equal: sumRevenue(byCategory) === sumRevenue(byMonth) && sumRevenue(byMonth) === byLoop,
});

When all three totals are the same and all_equal is true, the two pipelines and the loop agree. That does not prove every stage is right, but a wrong $unwind or a missing $match would almost certainly have made one of the totals differ.

Phase 4 done

We started with a question about shop pages that do not look alike. The catalog takes products of any shape and still refuses bad ones, sells the last laptop once, finds what shoppers ask for among 200,000 products, and turns orders into a report whose totals agree three ways. MongoDB did the work in each step, and the rules sit in the database, not in the code that calls it.