Để nhóm/ghép nối dữ liệu dựa trên hai cột khác nhau (ví dụ: CountryName1 và CountryName2), dùng $lookup tự join collection với chính nó.
Tạo collection demo132:
> db.demo132.insertOne({"CountryName1":"US","CountryName2":"UK",Value:50});
> db.demo132.insertOne({"CountryName1":"UK","CountryName2":"AUS",Value:10});
> db.demo132.insertOne({"CountryName1":"AUS","CountryName2":"US",Value:40});
Pipeline: lookup từ CountryName1 sang CountryName2, unwind, project tổng Value:
> db.demo132.aggregate([
{
"$lookup": {
"from": "demo132",
"localField": "CountryName1",
"foreignField": "CountryName2",
"as": "out"
}
},
{ "$unwind": "$out" },
{
"$project": {
"_id": 0,
"CountryName1": 1,
"total": { "$sum": ["$Value", "$out.Value"] }
}
}
])
Kết quả tổng giá trị cho mỗi quốc gia xuất phát:
{ "CountryName1" : "US", "total" : 90 }
{ "CountryName1" : "UK", "total" : 60 }
{ "CountryName1" : "AUS", "total" : 50 }