Aggregation Pipeline là framework xử lý dữ liệu đa stage, mỗi stage biến đổi document và truyền cho stage tiếp theo. Giống pipeline Unix: input → stage1 → stage2 → output.
Dữ liệu mẫu
> db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[65,78,36,90]});
> db.demo218.insertOne({"Name":"David","Branch":"ME",Marks:[56,45,42,51]});
> db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[78,65,89]});
Pipeline: Unwind → Match → Group
> db.demo218.aggregate([
{ "$unwind": "$Marks" },
{ "$match": { "Branch": "CS", "Marks": { "$gt": 88 } } },
{ "$group": {
"_id": "$_id",
"Branch": { "$first": "$Branch" },
"Marks": { "$first": "$Marks" }
}}
]);
Kết quả
{ "_id" : ObjectId("5e3e5f6c03d395bdc2134714"), "Branch" : "CS", "Marks" : 89 }
{ "_id" : ObjectId("5e3e5f4903d395bdc2134712"), "Branch" : "CS", "Marks" : 90 }
Giải thích từng stage:
- $unwind: "$Marks": Tách mảng Marks thành các document riêng (mỗi document 1 điểm). 3 doc gốc → 11 doc (4+4+3)
- $match: Lọc Branch="CS" VÀ Marks > 88. Chỉ còn 2 document (89 và 90)
- $group: Gom lại theo _id gốc, lấy Branch và Marks đầu tiên (vì đã lọc)
Các stage phổ biến:
$match- lọc (giống find)$project- chọn/biến đổi trường$group- gom nhóm, tính toán$sort- sắp xếp$limit/$skip- phân trang$unwind- tách mảng$lookup- join collection$addFields- thêm trường$facet- đa pipeline song song