Cast String to Date in MongoDB query

1.3k Views Asked by At

I have a collection with dates in string type, sush as:

{
 dateTime: "2015-25-15T10:10:10+02:00"
}
{
 dateTime: "2015-25-15T20:11:11+01:00"
}
...

and I need to manth dateTime by UTC Date in aggregation. I did find any way to cast string to date in query.

new ISODate(...) works just with literals

$where - is not applicable in aggregation

Is it possbile?

1

There are 1 best solutions below

0
On

With MongoDB v4.0+, you can use $toDate to convert your string fields to proper date objects.

With MongoDB v4.2+, you can put it in an update with aggregation pipeline.

db.collection.update({},
[
  {
    $set: {
      dateTime: {
        $toDate: "$dateTime"
      }
    }
  }
])

Mongo Playground


Note: There is invalid month 25 in your sample data. You may want to fix your datasource as commented by @user3561036.