2017-05-13 49 views
0

我正在執行彙總,並且正在研究如何在原始彙總方法內執行進一步細分總計SUM的能力。我目前在一段距離內返回總計事件,按集羣代碼分組。我希望將每個類別的總數細分。返回的彙總結果中的計數變量

我知道我可以執行$group查詢作爲這樣

var events = Events.aggregate(
     [ 
      { 
      $match : { 
       "location.loc" : { 
        $geoWithin : { 
        $centerSphere : [[long,lat], milesToRadian(radius) ] 
        } 
       } 
      } 
      }, 
      { 
      $group : { 
       _id : { 'cluster_code' : "$location.cluster_code"}, 
       count : { $sum : 1 } 
      } 
      } 
     ] 
    ) 

我知道我可以在我的$group查詢中增加一個額外的參數{"category" : "$category"}打破下來每個類別。然後,我可以執行分組方法來創建我正在尋找的正確格式。這感覺就像我可以改善查詢。

我想實現的是有一個SUM計數然後計數爲每個category。類似於:

{ 
    "_id": { 
     "cluster_code": "FK", 
    }, 
    "Run" : 2, 
    "Swim" : 1 
    "count": 3 
    }, 

這是可能在一個單一的聚合查詢嗎?

UPDATE

樣品僞文檔

{ 
_id : "df", 
"location" : { 
    //... 
}, 
"category" : "Run" 
} 
+0

你的示例文檔看起來像什麼? – Astro

+0

已更新上面。 'category'是頂級字符串 – Allreadyhome

回答

0

你可以試試下面聚集在管道版本3.4.4

$groupcluster_codecategory得到每個分組的計數。

$zip各自category鍵值對分別後跟$arrayToObject來創建輸出格式結構。

使用$addFieldscluster_code & totaldata

使用$replaceRootdata嵌入式文檔推廣到頂層。

aggregate(
{$group : { 
     _id : { "cluster_code" : "$location.cluster_code", category:"$category"}, 
     count : { $sum : 1 } 
    } 
}, 
{$group : { 
     _id : "$_id.cluster_code", 
     categorycount : { $push:{category:"$_id.category", count:"$count" }}, 
     total:{$sum:"$count"} 
    } 
}, 
{$addFields:{data: {$arrayToObject:{$zip:{inputs:["$categorycount.category", "$categorycount.count"]}}}}}, 
{$addFields:{"data.cluster_code": "$_id", "data.total":"$total"}}, 
{$replaceRoot:{newRoot:"$data"}} 
) 
+0

2個小組完成了這項工作,並且是有意義的 – Allreadyhome