title: MongoDB aggregate return count of 0 if no results
body: <p>I have the following MongoDB query that groups by date and result and gives a count.  I'd like to have the query also return a count of 0 for a particular date and result if data doesn't exist for that day.  </p>
  
  <p>For example I have the following result statuses: SUCCESS and FAILED.  If on the 21st there were no results of FAILED I would want a count returned of 0:</p>
  
  <pre><code>{
      "_id" : {
              "month" : 1,
              "day" : 21,
              "year" : 2014,
              "buildResult" : "FAILURE"
      },
      "count" : 0
  }
  </code></pre>
  
  <p>I've done something similar with a relational database and a calendar table, but I'm not sure how to approach this with MongoDB.  Is this possible or should I do something programatically after running the query?</p>
  
  <p>Here is an example of a document (simplified) in the database:</p>
  
  <pre><code>    {
              "_id" : ObjectId("52deab2fe4b0a491abb54108"),
              "type" : "build",
              "time" : ISODate("2014-01-21T17:15:27.471Z"),
              "data" : {
                      "buildNumber" : 43,
                      "buildDuration" : 997308,
                      "buildResult" : "SUCCESS"
              }
      }
  </code></pre>
  
  <p>Here is my current query:</p>
  
  <pre><code>db.builds.aggregate([
      { $match: { "data.buildResult" : { $ne : null} }},
      { $group: { 
          _id: { 
              month: { $month: "$time" },
              day: { $dayOfMonth: "$time" },
              year: { $year: "$time" }, 
              buildResult: "$data.buildResult",
          },
          count: { $sum: 1}
      } },
  
      { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1} }
  ])
  </code></pre>