title: MongoDB aggregation with multiple keys
body: <p>I have looked at a few similar questions/answer, e.g. <a href="https://stackoverflow.com/questions/16597812/how-do-i-count-multiple-keys-in-the-same-mongodb-aggregation-group-query">this one</a>, but I can't solve my case.</p>
  
  <p>I have a collection called <code>output</code> with documents of the form</p>
  
  <pre class="lang-json prettyprint-override"><code>{
    "_id" : ObjectId("55e06ac3cd8a52ac141012f2"),
    "Date" : ISODate("2010-11-02T00:00:00Z"),
    "output" : 0,
    "region" : "Gotham"
  }
  </code></pre>
  
  <p>These docs span multiple years and regions, I am trying to run an aggregate to get a breakdown of the total output, per region, per year. If I ignore the year I can get the first part using this</p>
  
  <pre class="lang-js prettyprint-override"><code>output.aggregate(
      [
        { "$group": {
          "_id": { region: "$region"},
          "output": { "$sum": "$output" }
        }}
      ],
      function(err,results) {
        console.log(results);
        db.close();
      }
    );
  </code></pre>
  
  <p>which gives me</p>
  
  <pre class="lang-sh prettyprint-override"><code>[ { _id: { region: 'Gotham' }, output: 2115715 },
    { _id: { region: 'London' }, output: 6799038 },
    { _id: { region: 'Tokyo' }, output: 8744809 }
  </code></pre>
  
  <p>but the output here is across several years, I want it broken down per year. </p>
  
  <p>I tried the following but it doesn't work</p>
  
  <pre class="lang-js prettyprint-override"><code>output.aggregate(
    [
      {
        $project : {
          year: {
            $year: "$Date"
          }
        }
      },
      {
        "$group": {
          "_id": {
            region: "$region",
            year: ""$year
          },
          "output": { "$sum": "$output" }
        }
      }
    ],
    function(err,results) {
      console.log(results);
      db.close();
    }
  );
  </code></pre>
  
  <p>this results in</p>
  
  <pre class="lang-sh prettyprint-override"><code>[ { _id: { year: 2015 }, output: 0 },
    { _id: { year: 2014 }, output: 0 },
    { _id: { year: 2013 }, output: 0 },
    { _id: { year: 2012 }, output: 0 },
    { _id: { year: 2009 }, output: 0 },
    { _id: { year: 2008 }, output: 0 },
    { _id: { year: 2011 }, output: 0 },
    { _id: { year: 2010 }, output: 0 } ]
  </code></pre>