Sử dụng $unwind nhiều lần và $group để aggregation trên cấu trúc lồng sâu. Tạo collection:
> db.aggregateDemo.insertOne({
"ProductInformation": [
{ "Product1": [ {"Amount":50}, {"Amount":90}, {"Amount":30} ] },
{ "Product1": [ {"Amount":200}, {"Amount":30}, {"Amount":40} ] },
{ "Product1": [ {"Amount":150}, {"Amount":190}, {"Amount":198} ] }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04df58150ee0e76c06a04d") }
> db.aggregateDemo.insertOne({
"ProductInformation": [
{ "Product1": [ {"Amount":100}, {"Amount":1002}, {"Amount":78} ] },
{ "Product1": [ {"Amount":75}, {"Amount":400}, {"Amount":600} ] },
{ "Product1": [ {"Amount":700}, {"Amount":500}, {"Amount":600} ] }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04df93150ee0e76c06a04e") }
Hiển thị cấu trúc phức tạp:
> db.aggregateDemo.find().pretty();
Aggregation: unwind 2 cấp, tìm Amount lớn nhất:
> db.aggregateDemo.aggregate([
{ $unwind: "$ProductInformation" },
{ $unwind: "$ProductInformation.Product1" },
{ $group: {
_id: null,
MaximumAmount: { $max: "$ProductInformation.Product1.Amount" }
}}
]);
Kết quả - Amount lớn nhất là 1002:
Quy trình: 1) Unwind ProductInformation (mảng cấp 1), 2) Unwind Product1 (mảng cấp 2), 3) Group tất cả tính $max trên Amount. Cấu trúc lồng nhau sâu cần unwind từng cấp.