SebastianG
SebastianG

Reputation: 9584

Convert ISO date to UNIX timestamp mongodb

There are hundreds of threads and operators to get date objects into ISO strings but can't find any resources on doing it the other way around as part of the mongoose/mongodb aggregation operators in Node.

I have a legacy mongodb 3.6 that's currently being used in production and I have a pipeline where I'm trying to convert a normal ISO date object from mongo into an UNIX timestamp so I can use it together with ngx-charts and other charts.

I can't use the $toDate, $convert operator or $dateFromString as the options that I need are not available in 3.6

So far I have tried variations of this:

      $project: {
        _id: 0,
        // name: '$_id._id',
        value: '$_id.count',
        name: new Date.parse('$_id.date').getTime(),
        min: '$min',
        max: '$max'
      }

but none of that worked as the aggregation is processed on the db and has no idea what that function is. I've looked at many operators and tried to convert to string first and then back to UNIX date but it doesn't seem to have anything available to convert into javascript/unix timestamp from that ISO date.

Upvotes: 5

Views: 2745

Answers (1)

Ashh
Ashh

Reputation: 46481

You can use below aggregation

db.getCollection('sessions').aggregate([
  { "$project": {
    "timestamp": {
      "$subtract": [ "$createdAt", new Date("1970-01-01") ]
    }
  }}
])

Upvotes: 3

Related Questions