Aggregation pipeline xử lý data qua nhiều stages như $match, $group, $project, $sort, $lookup, $unwind. Nó phù hợp reporting, transformation, analytics nhẹ và server-side data shaping.
Ví dụ tính revenue theo ngày:
javascript
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$day", revenue: { $sum: "$total" } } },
{ $sort: { _id: 1 } }
])Đặt $match sớm để giảm dữ liệu đi qua pipeline và tận dụng index.