title: MongoDB aggregation $divide computed fields
body: <p>I am trying to compute a percentage in a MongoDB query based on computed fields - not sure if this is possible or not.  What I'd like to be able to do is calculate the failure percentage: <code>(failed count / total) * 100</code></p>
  
  <p>Here are a few sample documents:</p>
  
  <pre><code>    {
              "_id" : ObjectId("52dda5afe4b0a491abb5407f"),
              "type" : "build",
              "time" : ISODate("2014-01-20T22:39:43.880Z"),
              "data" : {
                      "buildNumber" : 30,
                      "buildResult" : "SUCCESS"
              }
      },
      {
              "_id" : ObjectId("52dd9fede4b0a491abb5407a"),
              "type" : "build",
              "time" : ISODate("2014-01-20T22:15:07.901Z"),
              "data" : {
                      "buildNumber" : 4,
                      "buildResult" : "FAILURE"
              }
      },
      {
              "_id" : ObjectId("52dda153e4b0a491abb5407b"),
              "type" : "build",
              "time" : ISODate("2014-01-20T22:21:07.790Z"),
              "data" : {
                      "buildNumber" : 118,
                      "buildResult" : "SUCCESS"
              }
      }
  </code></pre>
  
  <p>Here is the query I am trying to work with.  The issue is in the FailPercent/$divide line:</p>
  
  <pre><code>db.col.aggregate([    
      { $match: { "data.buildResult" : { $ne : null } } },
      { $group: {          
          _id: {              
              month: { $month: "$time" },             
              day: { $dayOfMonth: "$time" },             
              year: { $year: "$time" },                       
          },         
          Aborted: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "ABORTED"]}, 1, 0]} },
          Failure: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "FAILURE"]}, 1, 0]} },
          Unstable: { $sum: { $cond : [{ $eq : ["$data.buildResult", "UNSTABLE"]}, 1, 0]} },
          Success: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "SUCCESS"]}, 1, 0]} },
          Total: { $sum: 1 },
          FailPercent: { $divide: [ "Failure", "Total" ] }
      } },     
      { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } } 
  ])
  </code></pre>