1. How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.
❓ Context: Demonstrate a multi-stage aggregation pipeline joining collections and computing analytics with Mongoose.
The MongoDB Aggregation Pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms documents into aggregated results.
Common Stages:
import { OrderModel } from './models/Order';
async function getCustomerTotalSpend() {
const result = await OrderModel.aggregate([
{ $match: { status: 'COMPLETED' } },
{
$lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'userInfo'
}
},
{ $unwind: '$userInfo' },
{
$group: {
_id: '$userId',
customerName: { $first: '$userInfo.name' },
totalSpent: { $sum: '$totalAmount' },
orderCount: { $sum: 1 }
}
},
{ $sort: { totalSpent: -1 } }
]);
return result;
}Place $match at the start of aggregation pipelines to leverage MongoDB indexes and reduce downstream pipeline processing size.