My aggregate query
'$dateDiff':
{
'startDate': '$updatedAt',
'endDate': new Date(),
'unit': "hour"
}
Example: My updatedAt is 10:00 (2023-06-08T10:00:00.502+00:00)
and my now is 1:50 (2023-06-08T13:54:00.502+00:00 )
My expected dateDiff is 3 but this is returning me 4.
Its rounding off but I want it to floor. How to achieve this ?
2
Answers
Use below as template
will return the number of hours between the
updatedAt
field and the current time. The$floor operator
will then round down the result to the nearest integer.The reason why your original query was returning 4 is because the
$dateDiff operator
rounds up the result. This is because the$dateDiff operator uses the IEEE 754 double-precision floating-point format
to represent numbers. This format has a limited number of digits after the decimal point, so rounding up is necessary to ensure that the result is accurate.The
$floor operator
, on the other hand, does not round up. It simply rounds down the result to the nearest integer. This is why the$floor operator w
ill return 3 in this case.$dateDiff pipeline stage
is not supported inMongoDB 4.0
. It was introduced inMongoDB 4.2.