Converting isodate to numerical value

Emii Khaos

Simply call the getTime() method, and you get the milliseconds since 1970/01/01

> var date_test = ISODate ("2013-07-26T22:35:40.373Z")
> date_test.getTime()
1374878140373

to convert milliseconds into date back, construct a new date object:

> new Date(1374878140373)
ISODate("2013-07-26T22:35:40.373Z")

Starting Mongo 4.0, the $toLong aggregation operator can be applied on a Date to get a timestamp:

// { mydate: ISODate("2019-06-23T15:52:29.576Z")
db.collection.aggregate({ $project: { timestamp: { $toLong: "$mydate" } } })
// { timestamp: NumberLong("1561305149576") }

and vice versa with $toDate:

// { timestamp: NumberLong("1561305149576") }
db.collection.aggregate({ $project: { mydate: { $toDate: "$timestamp" } } })
// { mydate: ISODate("2019-06-23T15:52:29.576Z") }