Aggregation pipeline là dây chuyền xử lý document qua nhiều "stage" nối tiếp — đầu ra của stage này là đầu vào của stage sau, giống băng chuyền nhà máy.
Các stage hay dùng:
- $match: lọc — đặt đầu pipeline để tận dụng index.
- $group: gom nhóm + tổng hợp ($sum, $avg, $push).
- $project: định hình lại, thêm field tính sẵn.
- $sort / $limit / $skip: sắp xếp, phân trang.
- $lookup: kiểu LEFT JOIN sang collection khác.
Tối ưu: đặt $match và $project càng sớm càng tốt để giảm số document phải xử lý phía sau (đặt $match sau $unwind là anti-pattern).
Vài stage nâng cao: $facet chạy nhiều nhánh song song trên cùng input (hợp faceted search — đếm theo danh mục + theo khoảng giá cùng lúc); $graphLookup đệ quy cho dữ liệu cây/đồ thị. Kiểm tra hiệu năng bằng .explain('executionStats') để xem có dùng index không.
The aggregation pipeline is an assembly line that processes documents through several sequential "stages" — each stage's output is the next stage's input, like a factory conveyor belt.
Common stages:
- $match: filter — place at the start of the pipeline to use indexes.
- $group: group + aggregate ($sum, $avg, $push).
- $project: reshape, add computed fields.
- $sort / $limit / $skip: sort, paginate.
- $lookup: a LEFT-JOIN-style stage into another collection.
Optimization: place $match and $project as early as possible to cut how many documents later stages handle ($match after $unwind is an anti-pattern).
A few advanced stages: $facet runs several branches in parallel on the same input (great for faceted search — count by category + by price range at once); $graphLookup does recursive lookups for tree/graph data. Check performance with .explain('executionStats') to see whether an index is used.