Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert ISODate to unix epoch in mongo aggregate

I have a field in mongo that is an ISODate. Is there an easy way to convert it to unix timestamps?

ie: ISODate("2018-03-30T13:06:05.739-07:00") => 1522440365739

like image 531
metakungfu Avatar asked Jan 28 '23 09:01

metakungfu


1 Answers

As of 4.0, you can use $toDecimal. $toInt would be too small for most timestamps nowadays.

db.collection.aggregate([{
  $project: {
    date: {'$toDecimal': '$date'}
  }
}])

This returns unix timestamps in milliseconds. To convert to seconds, use $divide by 1000

https://docs.mongodb.com/manual/reference/operator/aggregation/toDecimal/

like image 77
Allan Lei Avatar answered Feb 01 '23 18:02

Allan Lei