title: Mongoose aggregate - $subtract dates
body: <p>I'm having troubles with Mongoose aggregation when trying to subtract two dates to get milliseconds of the difference.</p>
  
  <p>Here's the document's structure:</p>
  
  <pre><code>DeliverySchema = new mongoose.Schema({
    hash: String,
    status: Number,
    insertedOn: {
      type: Date,
      default: Date.now
    },
    endedOn: {
      type: Date
    }
  }, {
    collection: 'Deliveries'
  });
  </code></pre>
  
  <p>This is the query:</p>
  
  <pre><code>var Delivery = mongoose.model('Delivery');
  
  return Delivery.aggregate([
      {
        $match: {
          'insertedOn': {$ne: null, $type: 9},
          'endedOn': {$ne: null, $type: 9}
        }
      },
      {$project: {duration: {$subtract: ["$endedOn", "$insertedOn"]}}},
      {
        $group: {
          _id: {
            day: {$dayOfMonth: "$insertedOn"},
            month: {$month: "$insertedOn"},
            year: {$year: "$insertedOn"}
          },
          count: {$sum: 1},
          durationAvg: {$avg: "$duration"}
        }
      },
      {$sort: {"_id.year": 1, "_id.month": 1, "_id.day": 1}}
    ])
  </code></pre>
  
  <p>This is the error i'm getting:</p>
  
  <pre><code>error: exception: can't convert from BSON type EOO to Date
  </code></pre>
  
  <p>The $match phase should filter all documents with insertedOn/endedOn fields null or non-Date, but it seems useless. I'm stuck, does anybody have any clues?
  I'm using Mongoose 4.0.1 (mongod 2.6.9 hosted on Mongolab) with Node 0.10.33.
  Thanks</p>
  
  <p>Thanks.</p>