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

รวมตามประเทศ รัฐ และเมืองในคอลเล็กชัน MongoDB ที่มีเอกสารหลายฉบับ


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

ในการรวมใน MongoDB ให้ใช้ aggregate() ให้เราสร้างคอลเลกชันที่มีเอกสาร -

> 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")
}

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -

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

ต่อไปนี้เป็นแบบสอบถามที่จะรวบรวมตามประเทศ รัฐ และเมือง −

> 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"
            }
         ]
      }
   ]
}