Pipeline Practice

Rank customer lifetime leaders

Joining before grouping lets descriptive fields participate in the summary key. The difficult part is keeping whole-order revenue intact while customer context is attached.

For completed orders, return the top three customers by revenue. Include `customerId`, `customerName`, `segment`, `revenue`, `orderCount`, and `averageOrder`.

Expected result: Three customer lifetime summaries, highest revenue first.

Example pipeline syntax

[
  { $match: { status: "completed" } },
  { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } }
]