Mongoose sum - $ subtracts dates

I'm having problems with Mongoose aggregation when trying to subtract two dates to get milliseconds of difference.

Here's the document structure:

DeliverySchema = new mongoose.Schema({
  hash: String,
  status: Number,
  insertedOn: {
    type: Date,
    default: Date.now
  },
  endedOn: {
    type: Date
  }
}, {
  collection: 'Deliveries'
});

      

This is the request:

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}}
  ])

      

This is the error I am getting:

error: exception: can't convert from BSON type EOO to Date

      

The $ match phase should filter all documents with insertOn / inatedOn null or non-Date fields, but this seems to be useless. I'm stuck, does anyone have any clues? I am using Mongoose 4.0.1 (mongod 2.6.9 on Mongolab) with Node 0.10.33. Thanks to

Thank.

+3


source to share


1 answer


Stage output $project

are documents that only contain a calculated field duration

. You must also include the insertedOn

and fields endedOn

so that they are available for use in the next step $group

:



{$project: {
    duration: {$subtract: ["$endedOn", "$insertedOn"]},
    endedOn: 1,
    insertedOn: 1
}}

      

+2


source







All Articles