3 Ways to Convert a String to a Date in MongoDB

If you have a MongoDB collection with dates stored as strings, you can convert those into the Date BSON type if required.

Below are three ways to convert a string into a Date in MongoDB.

Sample Data

The examples in this article use the following document in a collection called dogs:

{ "_id" : 1, "name" : "Fetch", "born" : "2021-01-03T23:30:15.123" }

We can see that the born field contains a date, but that date is stored as a string.

We can use the following aggregation pipeline operators to convert that string into a date.

The $dateFromString Operator

The $dateFromString aggregation pipeline operator was designed specifically for converting a date to a string.

It requires a dateString argument, which is the string that you want to be converted to a date.

Here’s an example of converting the string in the above collection to a date:

db.dogs.aggregate([ 
  {
    $project: {
        born: {
          $dateFromString: {
              dateString: '$born'
          }
        }
    }
  } 
])

Result:

{ "_id" : 1, "born" : ISODate("2021-01-03T23:30:15.123Z") }

We can see that the date is now wrapped in the ISODate helper, which means that it’s a Date object.

The $dateFromString operator accepts a handful of other arguments, all of which are optional. See MongoDB $dateFromString for more information and examples.

The $toDate Operator

The $toDate aggregation pipeline operator converts a value to a date. The value can be any type that that can be converted to a date, which is basically numbers, strings, and objectIds.

This article is about converting strings to dates, and so here’s an example of using $toDate to do just that:

db.dogs.aggregate([ 
  {
    $project: {
        "born": { 
          $toDate: "$born" 
        }
    }
  } 
])

Result:

{ "_id" : 1, "born" : ISODate("2021-01-03T23:30:15.123Z") }

See Mongo $toDate for more information and examples.

The $convert Operator

The $convert operator was specifically designed for converting between one type and another.

The input parameter specifies the field you want to convert, and the to parameter specifies the type you want to convert it to.

Example:

db.cats.aggregate(
  [
    {
      $project:
        { 
          result: 
          {
            $convert: { 
              input: "$born", 
              to: "date",
              onError: "An error occurred",
              onNull: "Input was null or empty" 
            }
          }
        }
    }
  ]
)

Result:

{ "_id" : 1, "result" : ISODate("2021-01-03T23:30:15.123Z") }

You might have noticed that the $convert operator also accepts onError and onNull parameters, which allows us to provide a message to use in the event of an error or a null value. This prevents the whole aggregation operation from halting, and it allows for a user-friendly error message within the output document.

See MongoDB $convert for more information and examples.