2016-04-26 75 views
0

蒙戈可以彙總這些數據:聚集嵌套組在蒙戈

cat  type  subtype count 
A  aa   1  10 
A  aa   2  20 
A  ac   4  15 
B  ac   3  30 
C  aa   3  40 
C  aa   5  50 
D  ac   6  60 
D  aa   2  70 

成文件看起來像下面這樣:

{ 
    'A': { 
      'count': 45, 
      'types': [ 
       {'type': 'aa', count:'30'}, 
       {'type': 'ac', count:'15'}, 
      ] 
    }, 
    'B': { 
      'count': 30, 
      'types': [ 
       {'type': 'ac', count:'30'}, 
      ] 
    }, 
    'C': { 
      'count': 90, 
      'types': [ 
       {'type': 'ac', count:'90'}, 
      ] 
    }, 
    'D': { 
      'count': 130, 
      'types': [ 
       {'type': 'ac', count:'60'}, 
       {'type': 'aa', count:'70'}, 
      ] 
    } 
    } 

基本上,創建嵌套組首先由type然後cat同時在每個分組級別運行總共count(如果有人熟悉D3,那麼它的rollup函數可以使用多個鍵)。

+0

簡短回答是!但爲什麼你使用你的數據作爲關鍵? – styvane

+0

,因爲這些數據將用於查找 –

+0

我不認爲你需要這樣做。我建議你改變你的結構:'{'name':'A','count':45,'types':[{'type':'aa',count:'30'},{'type' :'ac',count:'15'}]}' – styvane

回答

0

我意識到我可以在一個管道中有多個$ group命令後最終解決了這個問題。第一個$組合由(cat, type)合計,第二個$組合計算來自第一個合併組的結果(cat)。沿線的東西:

db.mycollection.aggregate([ 
    { 
     $group: { 
     _id: {'cat':'$cat','type':'$type'}, 
     'total': {$sum: $count} 
     } 
    }, 
    { 
     $group: { 
     _id: $_id.cat, 
     types: {$push: {type: $_id.type, total: $total}}, 
     total: {$sum: $total} 
     } 
    }, 
    { 
     $project: { 
     _id: 0, 
     cat: $_id.cat 
     types: 1, 
     total: 1 
     } 
    } 
])