Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

รวมข้อมูลตาม Country, State และ City ใน MongoDB

Aggregation ตาม Country, State และ City

Operation การรวมข้อมูล (Aggregation) จะจัดกลุ่มค่าจากหลายเอกสารเข้าด้วยกัน และสามารถดำเนินการหลากหลายบนข้อมูลที่จัดกลุ่มเพื่อส่งคืนผลลัพธ์เดียว

หากต้องการ Aggregate ใน MongoDB ให้ใช้ aggregate()

สร้าง Collection พร้อมข้อมูล

> db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8de96c954c74be91e6a1") }
> db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8e336c954c74be91e6a3") }
> db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8e636c954c74be91e6a4") }

แสดงเอกสารทั้งหมด

> db.demo620.find();

ผลลัพธ์:

{ "_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" }

คิวรี Aggregate ตาม Country, State และ City

> 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();

ผลลัพธ์:

{
    "_id" : "IND",
    "states" : [
        {
            "state" : "Delhi",
            "City" : [
                {
                    "City" : "Delhi"
                }
            ]
        },
        {
            "state" : "Maharashtra",
            "City" : [
                {
                    "City" : "Mumbai"
                }
            ]
        },
        {
            "state" : "Karnataka",
            "City" : [
                {
                    "City" : "Bangalore"
                }
            ]
        }
    ]
}