title: How to merge/join mongodb aggregate?
body: <p>Given this dataset:</p>
  
  <pre><code>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
  }])
  </code></pre>
  
  <p>I have two aggregate queries that give the total duration for each agent and the count of outgoing calls for each client:</p>
  
  <p>get outGoingCalls table:   </p>
  
  <pre><code>db.calls.aggregate([
    { $match: {  duration :{ $gt: 0 }, isFromOutside: false } },
    { $group: { _id: "$agent", outGoingCalls: { $sum: 1 } } },
    { $sort: { outGoingCalls: -1 } }
  ])
  </code></pre>
  
  <p>get totalDuration table:</p>
  
  <pre><code>db.calls.aggregate([
     { $group: { _id: "$agent", totalDuration: { $sum: "$duration" } } },
     { $sort: {totalDuration: -1 } }
  ])
  </code></pre>
  
  <p>How to merge/join these tables (or do only one aggregation) to have something like this:</p>
  
  <pre><code>[
    {_id: 0, totalDuration: ..., outGoingCalls: ...},
    {_id: 1, totalDuration: ..., outGoingCalls: ...},
    {_id: 2, totalDuration: ..., outGoingCalls: ...},
    ...
  ]
  </code></pre>