Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate timestamp difference in mongodb (in hours)?

Here's my data:

[
   {
       id: 1, 
       starttime: ISODate("2015-08-24T00:00:00.000Z"), 
       endtime: ISODate("2015-08-24T07:00:00.000Z")
   },
   {
       id: 2, 
       starttime: ISODate("2015-08-24T20:00:00.000Z"), 
       endtime: ISODate("2015-08-25T01:00:00.000Z")
   }
]

can I make a mongodb query to display duration (or in this case a difference operation) of starttime and endtime with results like:

[ {id:1, duration: 7}, {id: 2, duration: 5}]

Notice that timestamp can have different date so $hour(aggregation pipeline) might not work. Can anyone help ? Thank you

like image 535
DennyHiu Avatar asked Dec 14 '16 09:12

DennyHiu


People also ask

How does MongoDB calculate time difference?

The $dateDiff expression returns the integer difference between the startDate and endDate measured in the specified units . Durations are measured by counting the number of times a unit boundary is passed. For example, two dates that are 18 months apart would return 1 year difference instead of 1.5 years .

How do I calculate the time difference between two timestamps?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

How do I subtract two dates in MongoDB?

In MongoDB, you can use the $subtract aggregation pipeline operator to subtract numbers and/or dates. Specifically, $subtract can do the following three things: Subtract two numbers to return the difference. Subtract a number (in milliseconds) from a date and return the resulting date.

What format is MongoDB timestamp?

Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)


2 Answers

db.collectionname.aggregate([
  {$project: {
      duration: {$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]}
  }}
])
like image 145
DennyHiu Avatar answered Nov 15 '22 10:11

DennyHiu


Starting in Mongo 5.0, the $dateDiff aggregation operator perfectly fits your use case of producing the difference between two dates:

// { _id: 1, start: ISODate("2015-08-24T00:00:00Z"), end: ISODate("2015-08-24T07:00:00Z") }
// { _id: 2, start: ISODate("2015-08-24T20:00:00Z"), end: ISODate("2015-08-25T01:00:00Z") }
db.collection.aggregate([
  { $project:
    { duration:
      { $dateDiff: { startDate: "$start", endDate: "$end", unit: "hour" } }
    }
  }
])
// { "_id" : 1, "duration" : 7 }
// { "_id" : 2, "duration" : 5 }
like image 21
Xavier Guihot Avatar answered Nov 15 '22 10:11

Xavier Guihot