与mongodb多重聚合?

时间:2014-12-04 09:56:55

标签: mongodb aggregation-framework

我有以下文件:

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

我的第一个目标是按srcdst字段汇总它们,并获取与元组相关联的subject srcdst) 。这是我的疑问:

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

感谢此查询,我得到subjectsrc的每dst[ { "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 } } ] 进行分组,以便我可以拥有一个可以计算这些主题的字段?我的意思是,我希望得到一个结果:

{{1}}

我不知道这是否可能,因为我对mongodb很新;如果有人有任何线索,我会非常感激。

1 个答案:

答案 0 :(得分: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"
    }
}]);