title: Calculate a field's average after Mongo DB aggregate match and lookup query
body: <p>I have two Mongo DB collections, <em>req</em> and <em>res</em>.</p>
  
  <p>The format of <em>req</em> is - </p>
  
  <pre><code>{
      "_id" : ObjectId("asdasdasdasdasd"),
      "req" : {
          "url" : "/some/url",
          "method" : "GET",
      },
      "fieldA" : "ABCPQR",
      "time" : "2016-08-05T00:02:25.633Z",
  }
  </code></pre>
  
  <p>Collection <em>res</em> looks like this - </p>
  
  <pre><code>{
      "_id" : ObjectId("jhtuyiogjhknmkvjhjkbhj"),
      "time" : "2016-08-05T00:00:11.272Z",
      "duration" : 106,
      "fieldB" : "ABCPQR"
  }
  </code></pre>
  
  <p>What I want to do is.. For a certain kind of request, ie,  where <em>req.url</em> is same.. I want to calculate the average of <em>duration</em> field on <em>res</em> object.</p>
  
  <p>So I aggregate the <em>res</em> obejcts like this - </p>
  
  <pre><code>db.req.aggregate([
      { $match : { 'req.url' : '/some/url' } },
      { $lookup : { from : 'res', localField : 'fieldA', foreignField : 'fieldB', as : 'combined'} },
  ])
  </code></pre>
  
  <p>This is what the output looks like - </p>
  
  <pre><code>{
      "_id" : ObjectId("asdasdasdasdasd"),
      "req" : {
          "url" : "/device/apps/updates?sync=false",
          "method" : "POST",
      },
      "fieldA" : "34e92ab8-a037-4d39-b151-94cd3f1a34e7",
      "time" : "2016-08-05T00:00:11.166Z",
      "combined" : [ 
          {
              "_id" : ObjectId("57b452b70be0f24aec4cc204"),
              "time" : "2016-08-05T00:00:11.272Z",
              "duration" : 106,
              "fieldB" : "34e92ab8-a037-4d39-b151-94cd3f1a34e7"
          }
      ]
  }
  </code></pre>
  
  <p>Now to calculate, I added a <em>group</em> to the aggregation query - </p>
  
  <pre><code>db.req.aggregate([
      { $match : { 'req.url' : '/some/url' } },
      { $lookup : { from : 'res', localField : 'fieldA', foreignField : 'fieldB', as : 'combined'} },
      { $group: { _id: '$fieldA', avg : { $avg : '$combined.duration' } } }
  ])
  </code></pre>
  
  <p>But it produces no output at all. What am I doing wrong and how can I get the average of this <em>duration</em> field?</p>