如何合并/加入mongodb聚合?

时间:2015-06-09 14:56:13

标签: mongodb

鉴于此数据集:

db.calls.insert([{
  "agent": 2,
  "isFromOutside": true,
  "duration": 304
}, {
  "agent": 1,
  "isFromOutside": false,
  "duration": 811
}, {
  "agent": 0,
  "isFromOutside": true,
  "duration": 753
}, {
  "agent": 1,
  "isFromOutside": false,
  "duration": 593
}, {
  "agent": 3,
  "isFromOutside": true,
  "duration": 263
}, {
  "agent": 0,
  "isFromOutside": true,
  "duration": 995
}, {
  "agent": 0,
  "isFromOutside": false,
  "duration": 210
}, {
  "agent": 1,
  "isFromOutside": false,
  "duration": 737
}, {
  "agent": 2,
  "isFromOutside": false,
  "duration": 170
}, {
  "agent": 0,
  "isFromOutside": false,
  "duration": 487
}])

我有两个聚合查询,它们给出了每个代理的总持续时间以及每个客户端的传出呼叫计数:

离开GoCalls表:

db.calls.aggregate([
  { $match: {  duration :{ $gt: 0 }, isFromOutside: false } },
  { $group: { _id: "$agent", outGoingCalls: { $sum: 1 } } },
  { $sort: { outGoingCalls: -1 } }
])

获取totalDuration表:

db.calls.aggregate([
   { $group: { _id: "$agent", totalDuration: { $sum: "$duration" } } },
   { $sort: {totalDuration: -1 } }
])

如何合并/加入这些表(或只做一个聚合)以达到类似的效果:

[
  {_id: 0, totalDuration: ..., outGoingCalls: ...},
  {_id: 1, totalDuration: ..., outGoingCalls: ...},
  {_id: 2, totalDuration: ..., outGoingCalls: ...},
  ...
]

1 个答案:

答案 0 :(得分:1)

尝试以下聚合框架:

db.calls.aggregate([    
    {
        "$group": {
            "_id": "$agent",
            "outGoingCalls": {
                "$sum": {
                    "$cond": [
                        { 
                            "$and": [
                                {"$gt": ["$duration", 0 ]},
                                {"$eq": ["$isFromOutside", false ]}
                            ]
                        },
                        1,
                        0
                    ]
                }
            },
            "totalDuration": { "$sum": "$duration" }
        }
    },
    { 
        "$sort": {
            "totalDuration": -1,
            "outGoingCalls": -1
        } 
    }
])

<强>输出

/* 0 */
{
    "result" : [ 
        {
            "_id" : 0,
            "outGoingCalls" : 2,
            "totalDuration" : 2445
        }, 
        {
            "_id" : 1,
            "outGoingCalls" : 3,
            "totalDuration" : 2141
        }, 
        {
            "_id" : 2,
            "outGoingCalls" : 1,
            "totalDuration" : 474
        }, 
        {
            "_id" : 3,
            "outGoingCalls" : 0,
            "totalDuration" : 263
        }
    ],
    "ok" : 1
}