Sooner or later someone asks a question that no simple find can answer: *Who are our top five customers this year? How many orders came in each day? What is the average salary per department?* Doing that in JavaScript, by loading everything and looping, is slow and wastes memory. MongoDB can do the work inside the database with an aggregation pipeline. This lesson also covers transactions, which protect you when several changes must happen together.
A pipeline is a list of stages
Think of an assembly line. Documents enter the first stage, each stage transforms them, and the output of one becomes the input of the next. The most useful stages are: $match to keep only some documents, like find; $group to combine documents by a key and calculate totals; $sort and $limit to order and cut the list; $lookup to join another collection; $unwind to turn an array into separate documents; and $project to choose and rename the output fields.
import mongoose from 'mongoose';
// An aggregation pipeline is a list of stages. Each stage reads the output of the one before it.
// "Total sales and order count per customer, for paid orders this year, top 5."
export function topCustomersPipeline(year) {
return [
{ $match: { status: 'paid', createdAt: { $gte: new Date(`${year}-01-01`), $lt: new Date(`${year + 1}-01-01`) } } },
{ $group: { _id: '$customer', total: { $sum: '$amountCents' }, orders: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 5 },
{ $lookup: { from: 'users', localField: '_id', foreignField: '_id', as: 'customer' } },
{ $unwind: '$customer' },
{ $project: { _id: 0, name: '$customer.name', total: 1, orders: 1 } },
];
}
// const rows = await Order.aggregate(topCustomersPipeline(2026));
// A transaction makes several writes succeed together or not at all.
// It needs a replica set (MongoDB Atlas always is one; a plain local mongod is not unless you start it as one).
export async function transferStock(Product, fromId, toId, quantity) {
const session = await mongoose.startSession();
try {
await session.withTransaction(async () => {
const from = await Product.findOneAndUpdate(
{ _id: fromId, stock: { $gte: quantity } }, // only if enough stock: the check and the update are one step
{ $inc: { stock: -quantity } },
{ session, new: true },
);
if (!from) throw new Error('Not enough stock');
await Product.updateOne({ _id: toId }, { $inc: { stock: quantity } }, { session });
});
} finally {
await session.endSession();
}
}
Read the pipeline top to bottom. It keeps only paid orders of one year, groups them by customer while adding up amountCents and counting orders, sorts by total from largest to smallest, keeps five, joins the user documents to get names, flattens the joined array, and returns only the name, total and count. The first stage is always a $match if you can manage it, because it reduces the number of documents early, and a $match at the start can use an index.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install mongoose. - The pipeline is a plain array, so you can print it without a database. Save
db25-check.jsand run it.
import { topCustomersPipeline } from './db25-aggregate.js';
const stages = topCustomersPipeline(2026).map((s) => Object.keys(s)[0]);
console.log(stages.join(' -> '));
$match -> $group -> $sort -> $limit -> $lookup -> $unwind -> $project
Amounts are stored in cents as whole numbers, not as decimals such as 19.99. Computers cannot store many decimal fractions exactly, so adding prices as floating-point numbers drifts by tiny amounts. Whole numbers in the smallest unit stay exact. Convert to rupees or dollars only when you show the value.
Why transactions exist
Imagine moving stock from one warehouse to another. You subtract from the first and add to the second. If the server crashes between the two writes, the stock has vanished. A transaction groups writes so that either all of them are saved or none are. In the example, session.withTransaction runs the callback, commits if it finishes, and rolls everything back if it throws. The first update also contains the condition stock: { $gte: quantity }, so checking that there is enough stock and subtracting it happen in one step. That prevents two simultaneous requests from both thinking there is enough.
When you do not need a transaction
In MongoDB, a change to one document is atomic, even if it touches many fields. So if you design the data so that things that must change together live in one document, you often need no transaction at all. Use $inc, $push and findOneAndUpdate with a condition for counters and stock. Reach for a transaction when a rule really spans several documents, as with transfers, bookings and payments. Transactions cost performance, so keep them short and never call a slow external API inside one.
- Put
$matchfirst and$projectlast. - Store money as integers in the smallest unit.
- Use conditional updates, such as
stock >= quantity, to avoid race conditions. - Use a transaction when several documents must change together, and keep it short.
Your task
- Write a pipeline that counts orders per day for the last 30 days.
- Add a
$facetstage that returns both the top five and the overall total. - Write a transaction that creates an order and reduces stock, and make it fail on purpose to see the rollback.
How to check it worked
- You can name the seven stages in the example and say what each does.
- You can explain why the stock check and the update are one operation.
- You can say what a replica set has to do with transactions.