Các phép toán tổng hợp (aggregation) gom nhóm giá trị từ nhiều document và thực hiện nhiều phép toán trên dữ liệu đã gom để trả về kết quả đơn lẻ.
Tạo collection địa lý
> db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"});
> db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"});
> db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"});
Hiển thị dữ liệu
> db.demo620.find();
Kết quả:
{
"_id" : ObjectId("5e9a8de96c954c74be91e6a1"),
"Country" : "IND", "City" : "Delhi", "state" : "Delhi"
}
{
"_id" : ObjectId("5e9a8e336c954c74be91e6a3"),
"Country" : "IND", "City" : "Bangalore", "state" : "Karnataka"
}
{
"_id" : ObjectId("5e9a8e636c954c74be91e6a4"),
"Country" : "IND", "City" : "Mumbai", "state" : "Maharashtra"
}
Pipeline aggregate 2 cấp $group
> db.demo620.aggregate([
{
"$group": {
"_id": {
"Country": "$Country",
"state": "$state"
},
"City": {
"$addToSet": { "City": "$City" }
}
}
},
{
"$group": {
"_id": "$_id.Country",
"states": {
"$addToSet": {
"state": "$_id.state",
"City": "$City"
}
}
}
}
]).pretty();
Kết quả cấu trúc phân cấp:
{
"_id" : "IND",
"states" : [
{
"state" : "Delhi",
"City" : [ { "City" : "Delhi" } ]
},
{
"state" : "Maharashtra",
"City" : [ { "City" : "Mumbai" } ]
},
{
"state" : "Karnataka",
"City" : [ { "City" : "Bangalore" } ]
}
]
}
Giải thích:
- $group đầu tiên: Gom theo cặp (Country, state), dùng
$addToSetthu thập City duy nhất - $group thứ hai: Gom theo Country, thu thập các state kèm danh sách City của từng state
Kết quả cho thấy cấu trúc phân cấp: Quốc gia → Tỉnh/Thành → Danh sách thành phố.