2014-12-04 108 views
0

我有這樣的文件:用mongodb進行多重聚合?

{ 
    "src": "value", 
    "dst": "value", 
    "subject": "value" 
} 

我的第一個目標是通過srcdst領域聚集他們,並得到了subject S中的綁元組(srcdst)。這裏是我的查詢:

db.mycollection.aggreate([ 
    { 
    "$group": { 
     "_id": { 
    "src": "$src", 
    "dst": "$dst" 
     }, 
     "subjects": { 
     "$push": "$subject" 
     } 
    } 
    } 
]) 

由於這個查詢,每次都遇到subject每兩srcdst。這裏有一個期望的結果:

[ 
    { 
    "src": "distinct src", 
    "dst": "distinct dst", 
    "subjects": [ 
     { 
    "distinct subject", 
    "distinct subject", 
    "distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject" 
    "another distinct subject" 
     ] 
    }, 
    { 
    "src": "another distinct src", 
    "dst": "another distinct dst", 
    "subjects": [ 
    "distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject", 
    "another distinct subject" 
     ] 
    } 
] 

下一個步驟是:我怎麼能集團這些subject,所以我可以有一個統計這些科目領域?我的意思是,我希望得到這樣的結果:

[ 
    { 
    "src": "distinct src", 
    "dst": "distinct dst", 
    "subjects": [ 
     { 
    "subject": "distinct subject", 
    "count": 3 
     }, 
     { 
    "subject": "another distinct subject", 
    "count": 5 
     } 
    }, 
    { 
    "src": "another distinct src", 
    "dst": "another distinct dst", 
    "subjects": [ 
     { 
    "subject": "distinct subject", 
    "count": 1 
     }, 
     { 
    "subject": "another distinct subject", 
    "count": 11 
     } 
    } 
] 

我不知道這是否可行與否,因爲我是很新,MongoDB的;如果任何人有任何線索,但我很感激。

回答

1

爲了達到最終效果,我認爲你應該首先考慮每個主題。以下供您參考:

db.collection.aggregate([{ 
    $group : { 
     _id : { 
      src : "$src", 
      dst : "$dst", 
      subject : "$subject" 
     }, 
     count : { 
      $sum : 1 
     } 
    } 
}, { 
    $group : { 
     _id : { 
      src : "$_id.src", 
      dst : "$_id.dst" 
     }, 
     subjects : { 
      $push : { 
       subject : "$_id.subject", 
       count : "$count" 
      } 
     } 
    } 
}, { 
    $project : { 
     _id : 0, 
     src : "$_id.src", 
     dst : "$_id.dst", 
     subjects : "$subjects" 
    } 
}]);