Mini Project: Store Dashboard
In this project you build the data layer of a sales dashboard for TAD Coffee: the numbers a shop manager looks at every morning. You will combine almost everything from the course: filters, aggregation stages, $lookup, $facet, $merge, indexes and validation.
The dashboard needs:
- headline KPIs: revenue, number of orders, average order value, open orders,
- revenue per product category,
- the top customers, with their names,
- a restock list of products that are running out,
- all of it stored in a
dashboardcollection that the web page reads with one cheapfindOne.
Each step is a separate playground. Because every run starts from fresh data, later steps repeat the code they need from earlier ones.
Step 1: headline KPIs
Revenue only counts delivered and shipped orders; "open" orders are those still processing. One $facet computes both from a single pass over orders:
const kpis = db.orders.aggregate([
{ $facet: {
sales: [
{ $match: { status: { $in: ['delivered', 'shipped'] } } },
{ $group: { _id: null, revenue: { $sum: '$total' }, orders: { $sum: 1 }, avg: { $avg: '$total' } } }
],
open: [{ $match: { status: 'processing' } }, { $count: 'n' }]
} },
{ $project: {
revenue: { $first: '$sales.revenue' },
orders: { $first: '$sales.orders' },
avgOrder: { $round: [{ $first: '$sales.avg' }, 2] },
openOrders: { $ifNull: [{ $first: '$open.n' }, 0] }
} }
]).toArray()[0];
print(kpis);{ revenue: 605.5, orders: 13, avgOrder: 46.58, openOrders: 5 }
$ifNull protects against an empty facet: if no order were processing, $count would output nothing and openOrders would be missing.
Step 2: revenue per category
Line items don't store the category, so we join each item to its product. Grouping by category and computing each category's share of the revenue:
const byCategory = db.orders.aggregate([
{ $match: { status: { $in: ['delivered', 'shipped'] } } },
{ $unwind: '$items' },
{ $lookup: { from: 'products', localField: 'items.productId', foreignField: '_id', as: 'product' } },
{ $set: { category: { $first: '$product.category' } } },
{ $group: { _id: '$category', revenue: { $sum: { $multiply: ['$items.qty', '$items.price'] } } } },
{ $group: { _id: null, total: { $sum: '$revenue' }, rows: { $push: '$ROOT' } } },
{ $unwind: '$rows' },
{ $project: {
_id: '$rows._id',
revenue: '$rows.revenue',
share: { $round: [{ $multiply: [{ $divide: ['$rows.revenue', '$total'] }, 100] }, 1] }
} },
{ $sort: { revenue: -1 } }
]).toArray();
byCategory.forEach(c => print(c._id.padEnd(10), String(c.revenue).padStart(6), c.share + '%'));coffee 243 40.1%
equipment 177 29.2%
tea 96 15.9%
snacks 89.5 14.8%
The trick for percentages: a second $group with _id: null collects the total and the rows ($ROOT is the whole current document), and $unwind spreads the rows out again with the total attached.
Step 3: top customers
The three customers with the highest revenue, with their name and tier from customers. Group first, then join only the three winners, so $lookup runs three times instead of once per order:
db.orders.createIndex({ customerId: 1 });
const top = db.orders.aggregate([
{ $match: { status: { $in: ['delivered', 'shipped'] } } },
{ $group: { _id: '$customerId', spent: { $sum: '$total' }, orders: { $sum: 1 } } },
{ $sort: { spent: -1, _id: 1 } },
{ $limit: 3 },
{ $lookup: { from: 'customers', localField: '_id', foreignField: '_id', as: 'c' } },
{ $project: { _id: 0, name: { $first: '$c.name' }, tier: { $first: '$c.tier' }, orders: 1, spent: 1 } }
]).toArray();
print(top);[
{ spent: 142.5, orders: 3, name: 'Ada Lovelace', tier: 'gold' },
{ spent: 138, orders: 2, name: 'Margaret Hamilton', tier: 'silver' },
{ spent: 104.5, orders: 2, name: 'Grace Hopper', tier: 'gold' }
]
Step 4: the restock list
A product needs restocking when it is sold out or when it has fewer units than it sold over the whole period. Units sold come from the order items; $lookup with a pipeline computes them per product:
const restock = db.products.aggregate([
{ $lookup: {
from: 'orders',
let: { pid: '$_id' },
pipeline: [
{ $match: { status: { $ne: 'cancelled' } } },
{ $unwind: '$items' },
{ $match: { $expr: { $eq: ['$items.productId', '$pid'] } } },
{ $group: { _id: null, units: { $sum: '$items.qty' } } }
],
as: 'sales'
} },
{ $set: { sold: { $ifNull: [{ $first: '$sales.units' }, 0] } } },
{ $match: { $expr: { $or: [{ $eq: ['$stock', 0] }, { $lt: ['$stock', '$sold'] }] } } },
{ $project: { _id: 1, name: 1, stock: 1, sold: 1 } },
{ $sort: { stock: 1, _id: 1 } }
]).toArray();
restock.forEach(p => print(String(p._id).padStart(2), p.name.padEnd(18), 'stock', p.stock, '| sold', p.sold)); 4 Colombia Supremo stock 0 | sold 2
8 Chamomile Calm stock 0 | sold 0
14 Milk Frother stock 0 | sold 0
18 Oat Cookies stock 0 | sold 2
In the sample data no product has fewer units than it sold, so the list contains just the four sold-out products. The Burr Grinder comes closest, with 6 units left and 2 sold; the Gooseneck Kettle (4 left) sold none, because its only order was cancelled.
Step 5: store the dashboard
Running these pipelines on every page view would be wasteful. Instead, a scheduled job computes the dashboard once (say every 10 minutes) and upserts it into a dashboard collection. A validator makes sure a buggy job can never store a broken dashboard. The page then reads one small document:
db.createCollection('dashboard', {
validator: { $jsonSchema: {
required: ['_id', 'generatedAt', 'kpis', 'topCustomers', 'restock'],
properties: {
kpis: { bsonType: 'object', required: ['revenue', 'orders'] },
topCustomers: { bsonType: 'array', maxItems: 10 },
restock: { bsonType: 'array' }
}
} }
});
function buildDashboard(now) {
const shipped = { status: { $in: ['delivered', 'shipped'] } };
const [kpis] = db.orders.aggregate([
{ $match: shipped },
{ $group: { _id: null, revenue: { $sum: '$total' }, orders: { $sum: 1 } } },
{ $project: { _id: 0 } }
]).toArray();
const topCustomers = db.orders.aggregate([
{ $match: shipped },
{ $group: { _id: '$customerId', spent: { $sum: '$total' } } },
{ $sort: { spent: -1, _id: 1 } },
{ $limit: 3 },
{ $lookup: { from: 'customers', localField: '_id', foreignField: '_id', as: 'c' } },
{ $project: { _id: 0, name: { $first: '$c.name' }, spent: 1 } }
]).toArray();
const restock = db.products.find({ stock: 0 }, { _id: 0, name: 1 }).sort({ name: 1 }).toArray().map(p => p.name);
db.dashboard.replaceOne(
{ _id: 'store' },
{ generatedAt: now, kpis, topCustomers, restock },
{ upsert: true }
);
}
buildDashboard(ISODate('2026-06-04T06:00:00Z'));
// a new delivery arrives and an order is delivered, then the job runs again
db.products.updateOne({ _id: 4 }, { $set: { stock: 30 } });
db.orders.updateOne({ _id: 1016 }, { $set: { status: 'delivered' } });
buildDashboard(ISODate('2026-06-04T06:10:00Z'));
print(db.dashboard.findOne({ _id: 'store' }));
print(db.dashboard.countDocuments(), 'dashboard document');{
_id: 'store',
generatedAt: ISODate('2026-06-04T06:10:00.000Z'),
kpis: { revenue: 679, orders: 14 },
topCustomers: [
{ spent: 178, name: 'Grace Hopper' },
{ spent: 142.5, name: 'Ada Lovelace' },
{ spent: 138, name: 'Margaret Hamilton' }
],
restock: [ 'Chamomile Calm', 'Milk Frother', 'Oat Cookies' ]
}
1 dashboard document
The second run replaced the document in place: revenue grew by order 1016's 73.5 (from 605.5 to 679), Grace Hopper, who placed that order, moved to the top of the customer list, and Colombia Supremo left the restock list.
Ideas to extend the project
- Add a
daily_salescollection maintained with$merge(see $out and $merge) and a seven-day chart. - Store the dashboard per month (
_id: '2026-05') to keep history. - Expose
db.dashboard.findOne()through a small Express route using the Node.js driver. - Check your pipelines with
explain()and add indexes onorders.statusandorders.date.
Test yourself
Why does step 3 run $lookup after $limit?
- $lookup must be last
- So the join runs for 3 customers instead of for every order
- $limit only works after $lookup
- It changes the result
What does $ROOT refer to in a pipeline?
- The first document of the collection
- The whole current document
- The database root
- The pipeline's first stage
Why store the computed dashboard in a collection?
- Aggregations can't be read by web pages
- Reading one precomputed document is much cheaper than running the pipelines on every page view
- MongoDB forbids repeated aggregations
- To avoid indexes