How to calculate timestamp difference in hours with MongoDB?


To calculate timestamp difference, use aggregate framework. Let us first create a collection with documents −

> db.timestampDifferenceDemo.insertOne({
   "MovieBeginningTime": new ISODate("2019-05-12 10:20:30"),
   "MovieEndingTime":new ISODate("2019-05-12 12:30:20")
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ba1f6d78f205348bc644")
}
> db.timestampDifferenceDemo.insertOne({
   "MovieBeginningTime": new ISODate("2019-05-12 04:00:00"),
   "MovieEndingTime":new ISODate("2019-05-12 07:10:00")
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ba3b6d78f205348bc645")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.timestampDifferenceDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd7ba1f6d78f205348bc644"),
   "MovieBeginningTime" : ISODate("2019-05-12T10:20:30Z"),
   "MovieEndingTime" : ISODate("2019-05-12T12:30:20Z")
}
{
   "_id" : ObjectId("5cd7ba3b6d78f205348bc645"),
   "MovieBeginningTime" : ISODate("2019-05-12T04:00:00Z"),
   "MovieEndingTime" : ISODate("2019-05-12T07:10:00Z")
}

Following is the query to calculate timestamp difference in MongoDB (in hours) −

> db.timestampDifferenceDemo.aggregate([
   {$project: {
      DifferenceInHours: {$divide: [{$subtract: ["$MovieEndingTime", "$MovieBeginningTime"]}, 3600000]}
   }}
]);

This will produce the following output −

{ "_id" : ObjectId("5cd7ba1f6d78f205348bc644"), "DifferenceInHours" : 2.1638888888888888 }
{ "_id" : ObjectId("5cd7ba3b6d78f205348bc645"), "DifferenceInHours" : 3.1666666666666665 }

Updated on: 30-Jul-2019

738 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements