Difference between "now" and a given date with MongoDB?

To calculate the difference between the current date and a given date in MongoDB, use the $subtract operator with new Date() to get the current timestamp and subtract the stored date field.

Syntax

db.collection.aggregate([
    {
        $project: {
            "differenceInMilliseconds": {
                $subtract: [new Date(), "$dateField"]
            },
            "differenceInDays": {
                $divide: [
                    { $subtract: [new Date(), "$dateField"] },
                    1000 * 60 * 60 * 24
                ]
            }
        }
    }
]);

Sample Data

db.demo734.insertMany([
    { GivenDate: new Date("2020-01-10") },
    { GivenDate: new Date("2020-02-20") },
    { GivenDate: new Date("2010-12-01") },
    { GivenDate: new Date("2020-05-01") }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

View Sample Data

db.demo734.find();
{ "_id": ObjectId("..."), "GivenDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("..."), "GivenDate": ISODate("2020-02-20T00:00:00Z") }
{ "_id": ObjectId("..."), "GivenDate": ISODate("2010-12-01T00:00:00Z") }
{ "_id": ObjectId("..."), "GivenDate": ISODate("2020-05-01T00:00:00Z") }

Example: Calculate Date Difference

Get the difference between current date and stored dates in both milliseconds and days ?

db.demo734.aggregate([
    {
        $project: {
            "differenceMilli": {
                $subtract: [
                    new Date(),
                    "$GivenDate"
                ]
            }
        }
    },
    {
        $project: {
            "differenceMilli": 1,
            "differenceInDays": {
                $divide: [
                    "$differenceMilli",
                    1000 * 60 * 60 * 24
                ]
            }
        }
    }
]);
{ "_id": ObjectId("..."), "differenceMilli": NumberLong("9802234864"), "differenceInDays": 113.45 }
{ "_id": ObjectId("..."), "differenceMilli": NumberLong("6259834864"), "differenceInDays": 72.45 }
{ "_id": ObjectId("..."), "differenceMilli": NumberLong("297255034864"), "differenceInDays": 3440.45 }
{ "_id": ObjectId("..."), "differenceMilli": NumberLong("125434864"), "differenceInDays": 1.45 }

Key Points

  • $subtract returns the difference in milliseconds between two dates
  • new Date() gets the current timestamp during query execution
  • Divide by 1000 * 60 * 60 * 24 to convert milliseconds to days
  • Use multiple $project stages to calculate both milliseconds and days

Conclusion

Use $subtract with new Date() to calculate date differences in MongoDB. The result is in milliseconds, which can be converted to days by dividing by the appropriate conversion factor.

Updated on: 2026-03-15T03:53:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements