skip to Main Content

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


  1. db.collection.aggregate([
      {
        $project: {
          dateDiff: {
            // floor the result of division
            $floor: {
              // divide the difference of dates by 1000 * 60 * 60 to get the difference in hours
              $divide: [
                {
                  // subtract the dates to get the difference in milliseconds
                  $subtract: [new Date(), '$updatedAt'],
                },
                1000 * 60 * 60,
              ],
            },
          },
        },
      },
    ]);
    
    Login or Signup to reply.
  2. Use below as template

    db.collection.aggregate([   {
        $match: {
          updatedAt: {
            $date: {
              $year: 2023,
              $month: 6,
              $day: 8,
              $hour: 10,
            },
          },
        },   },   {
        $dateDiff: {
          startDate: '$updatedAt',
          endDate: new Date(),
          unit: "hour",
        },   },   {
        $floor: {
          $dateDiff: {
            startDate: '$updatedAt',
            endDate: new Date(),
            unit: "hour",
          },
        },   }, ]);
    

    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 will return 3 in this case.
    $dateDiff pipeline stage is not supported in MongoDB 4.0. It was introduced in MongoDB 4.2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search