Aggregation pipeline xử lý dữ liệu qua nhiều stage nối tiếp nhau — giống dây chuyền: output của stage này là input của stage kế. Các stage hay gặp: $match, $group, $project, $sort, $lookup, $unwind. Hợp cho báo cáo, biến đổi dữ liệu, analytics nhẹ và xử lý ngay phía server.
Ví dụ tính doanh thu theo ngày:
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$day", revenue: { $sum: "$total" } } },
{ $sort: { _id: 1 } }
])Lưu ý: đặt $match càng sớm càng tốt để lọc bớt dữ liệu trước, vừa nhẹ cho các stage sau vừa tận dụng được index.
The aggregation pipeline processes data through a series of stages — like an assembly line, where each stage's output is the next stage's input. Common stages: $match, $group, $project, $sort, $lookup, $unwind. Useful for reporting, data transformation, lightweight analytics, and server-side processing.
Example computing revenue by day:
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$day", revenue: { $sum: "$total" } } },
{ $sort: { _id: 1 } }
])Note: put $match as early as possible to filter data first — it lightens later stages and lets the query use an index.