title: Mongodb Aggregate calculate average and add it to the document
body: <p>I have <code>websites</code> which contains 2 documents:</p>
  
  <pre><code>{
      "_id" : ObjectId("58503934034b512b419a6eab"),
      "website" : "https://www.stackoverflow.com",
      "name" : "Stack Exchange",
      "keywords" : [ 
          "helping", 
          "C#", 
          "PYTHON"
      ]
  }
  
  {
      "_id" : ObjectId("58503934034b512b419a6eab"),
      "website" : "https://www.google.com.com",
      "name" : "Stack Exchange",
      "keywords" : [ 
          "search", 
          "engine", 
      ]
  }
  </code></pre>
  
  <p>I also have another <code>seo_tracking</code> which contains:</p>
  
  <pre><code>{
      "_id" : ObjectId("587373d6f6325811c8a0b3ad"),
      "position" : "2",
      "real_url" : "https://www.stackoverflow.com",
      "created_at" : ISODate("2017-01-09T11:28:22.104Z"),
      "keyword" : "helping"
  },
  {
     "_id" : ObjectId("587373d6f6325811c8a0b3ad"),
     "position" : "4",
     "real_url" : "https://www.stackoverflow.com",
     "created_at" : ISODate("2017-01-09T11:28:22.104Z"),
     "keyword" : "C#"
  }
  </code></pre>
  
  <p>etc.. This contains around 100+ documents </p>
  
  <p>What I want to do is is aggregate the <code>seo_tracking</code> with <code>website</code> on the specific URL (<code>www.stackexchange</code> (in <code>websites</code>) would match <code>www.stackoverflow.com</code> in (<code>seo_tracking</code>)) which I can do fine. However, I would like to return for each of the <code>websites</code> the following:</p>
  
  <pre><code>{
      "_id" : ObjectId("587373d6f6325811c8a0b3ad"),
      "website":"https://www.stackoverflow.com", 
      "avg_position" : "2"
  }
  </code></pre>
  
  <p>Then for Google etc.. Even if the <code>avg_position</code> is 0 .. I have tried the following:</p>
  
  <pre><code>db.seo_tracking.aggregate([
  
      {
          $lookup:
          {
              from: "websites", 
              localField: "real_url", 
              foreignField: "website", 
              as: "post_websites"
           },
       },
       {
          "$group": {
             _id:null, 
            avg_position:{$avg:"$position"}
            }
        } 
  ])
  </code></pre>
  
  <p>However, this just produces:</p>
  
  <pre><code>{
      "_id" : null,
      "avg_position" : 2.0
  }
  </code></pre>
  
  <p>What I need to do is have <code>website</code> and ideally also need the <code>ID</code> </p>
  
  <p>Any ideas to where I'm going wrong here?</p>