Difference between “now” and a given date with MongoDB?


To get the difference between dates in MongpDB, use aggregate(). Let us create a collection with documents −

> db.demo734.insertOne({GivenDate:new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead4f1a57bb72a10bcf064e")
}
> db.demo734.insertOne({GivenDate:new ISODate("2020-02-20")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead4f2157bb72a10bcf064f")
}
> db.demo734.insertOne({GivenDate:new ISODate("2010-12-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead4f2b57bb72a10bcf0650")
}
> db.demo734.insertOne({GivenDate:new ISODate("2020-05-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead506f57bb72a10bcf0651")
}

Display all documents from a collection with the help of find() method −

> db.demo734.find();

This will produce the following output −

{ "_id" : ObjectId("5ead4f1a57bb72a10bcf064e"), "GivenDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5ead4f2157bb72a10bcf064f"), "GivenDate" : ISODate("2020-02-20T00:00:00Z") }
{ "_id" : ObjectId("5ead4f2b57bb72a10bcf0650"), "GivenDate" : ISODate("2010-12-01T00:00:00Z") }
{ "_id" : ObjectId("5ead506f57bb72a10bcf0651"), "GivenDate" : ISODate("2020-05-01T00:00:00Z") }

Following is the query to get the difference between “now” and a given date −

> db.demo734.aggregate([
...    {$project: {
...
...       "differenceMilli": {
...
...          $subtract:[
...             new ISODate(),
...             "$GivenDate"
...          ]
...       }
...    }
... },
... {$project: {
...
...       "differenceMilli": 1,
...       "differenceindays": {
...          $divide: [
...             "$differenceMilli",
...             1000 * 60 * 60 * 24
...          ]
...       }
...    }
... }]
... )

This will produce the following output −

{ "_id" : ObjectId("5ead4f1a57bb72a10bcf064e"), "differenceMilli" : NumberLong("9802234864"), "differenceindays" : 113.45179240740741 }
{ "_id" : ObjectId("5ead4f2157bb72a10bcf064f"), "differenceMilli" : NumberLong("6259834864"), "differenceindays" : 72.45179240740741 }
{ "_id" : ObjectId("5ead4f2b57bb72a10bcf0650"), "differenceMilli" : NumberLong("297255034864"), "differenceindays" : 3440.4517924074075 }
{ "_id" : ObjectId("5ead506f57bb72a10bcf0651"), "differenceMilli" : NumberLong(125434864), "differenceindays" : 1.4517924074074073 }

Updated on: 30-Jun-2020

940 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements