2016-04-26 9 views
0

Kann Mongo diese Daten aggregieren:in verschachtelte Gruppen in Mongo Aggregieren

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 

in ein Dokumenten, die die aussehen wie folgt:

{ 
    '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'}, 
      ] 
    } 
    } 

Grundsätzlich erstellt verschachtelte Gruppen zuerst von type und dann durch cat während die Summe von count auf jeder Gruppierungsebene (wenn jemand mit D3 vertraut ist, das ist, was seine rollup Funktion mit mehreren Schlüsseln tun kann).

+0

Kurze Antwort JA! Aber warum benutzt du deine Daten als Schlüssel? – styvane

+0

, weil diese Daten für Nachschlagezwecke verwendet werden –

+0

Ich glaube nicht, dass Sie dies tun müssen. Ich schlage vor, dass Sie Ihre Struktur wie folgt ändern: '{'name': 'A', 'count': 45, 'types': [{'type': 'aa', count: '30 '}, {' type ' : 'ac', count: '15 '}]} ' – styvane

Antwort

0

Ich endete nach der Erkenntnis, dass ich mehrere $ Gruppenbefehle in einer Pipeline haben kann. Die erste $ -Gruppe aggregiert nach (cat, type) und die zweite $ -Gruppe aggregiert die Ergebnisse aus der ersten $ (cat). Etwas in der Art von:

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 
     } 
    } 
]) 
Verwandte Themen