Search code examples
stringmongodbtimeprojectionmilliseconds

how to convert milliseconds into HH:MM:SS format in mongodb(3.4 version)


I am projecting a field as i want the difference between DateOfOcurrance and current time. Then I want to compare the diff_time field with one time which is in String format(HH:MM:SS) as I want those documents which have less than 15mins diff_time, but not getting.

{$project: {diff_time:{ $subtract: ["$DateOfOcurrance", new Date("2020-02-14")]}}},
{"$match": {"diff_time": { "$lt": "00:15:00" }}}

Solution

  • Dates are stored as the number of milliseconds since epoch. When you subtract one date from another, you get a NumberLong containing the difference in milliseconds.

    To find differences less than 15 minutes, use:

    {"$match": {"diff_time": { "$lt": 900000 }}}
    

    (900000 = number of milliseconds in 15 minutes)