2014-12-04 36 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" 
    } 
}]);