Home > Enterprise >  How to calculate time different in start and end date in MongoDB
How to calculate time different in start and end date in MongoDB

Time:11-18

I have a two date fields start and end dates. I need to get this two dates date difference to split days & hours & minutes & seconds in mongoDB

Collection Records

[
  {
    "startDate": {
      "$date": {
        "$numberLong": "1630926969195"
      }
    },
    "endDate": {
      "$date": {
        "$numberLong": "1648558585308"
      }
    }
  }
]

I need results of below.

Results

{
    days: 204,
    hours: 1,
    minutes: 40,
    seconds: 16
}

Play Ground Link

CodePudding user response:

To achieve this result you will need to use the arithmetic operators to calculate the deltas. To calculate hours for example:

      hours: {
        "$subtract": [
          "$totalHours",
          {
            "$multiply": [
              "$days",
              24
            ]
          }
        ]
      }

While you could do this in a single stage, the nesting may get a little messy. I chose to use a series of $addFields stages to do this instead for readability purposes. Playground demonstration here, with output from your sample input document being:

[
  {
    "days": 204,
    "hours": 1,
    "minutes": 40,
    "seconds": 16
  }
]
  • Related