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
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 .
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.
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.
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)
db.collectionname.aggregate([
{$project: {
duration: {$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]}
}}
])
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With