Custom field with date calculation

I am trying to add a custom field to calculate the hour difference between current utc time and a date field in my collection. However, I am unable to specify the right expression. Given that there is a field called EventTime, I am trying to do this:

{
  $divide: [
    {
      $subtract: [
        new Date(),
        "$EventTime"
      ]
    },
    1000 * 60 * 60
  ]
}
`
However, I keep getting this error: 
`(TypeMismatch) Executor error during getMore :: caused by :: can't $subtract date from string, correlationID = 17b5aa0a81597aa7ed3893a3`

I don’t think you can mix in JavaScript expressions like new Date() in calculated fields. I would suggest doing this using $dateDiff and using $$NOW to represent the current time.

@tomhollander Thank you for your response.
I tried this:
``{
$dateDiff: {
startDate: “$$NOW”,
endDate: “$FulfillmentSlaUtc”,
unit: day
}
}It is giving me anInvalid Query` error on the portal.

The value for unit needs to be quoted, e.g. unit: "day"

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.