在包含多個文件的 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"
            }
         ]
      }
   ]
}

更新於: 2020 年 5 月 12 日

808 次瀏覽

開啟你的 事業

完成課程獲得認證

開始學習
廣告