3 Ways to Convert a Date to a String in MongoDB

MongoDB has a Date BSON type that allows you to store dates as dates.

You can also store dates as strings, if that’s what you need.

Taking it a step further, you can also convert a Date to a string.

This article presents three ways to convert a Date to a string in MongoDB.

Sample Data

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

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

Notice that the born field is a Date. The following examples use various aggregation pipeline operators to convert this field into a string.

The $dateToString Operator

The $dateToString aggregation pipeline operator is the most obvious place to start.

As its name implies, its sole purpose is to convert a Date to a string (and return the result).

Example:

db.cats.aggregate(
   [
     {
       $project: {
         _id: 0,
          dateString: { $dateToString: { format: "%Y-%m-%dT%H:%M:%S.%LZ", date: "$born" } }
       }
     }
   ]
)

Result:

{ "dateString" : "2021-01-03T23:30:15.123Z" }

Here, I provided a format string to specify the format of the resulting string. In this case, I used %Y-%m-%dT%H:%M:%S.%LZ, which is the default format. If I hadn’t specified a format, this is the format that it would have used.

You can move those format specifiers around to suit your resulting string.

For example, we could do this:

db.cats.aggregate(
   [
     {
       $project: {
         _id: 0,
          dateString: { $dateToString: { format: "%d/%m/%Y", date: "$born" } }
       }
     }
   ]
)

Result:

{ "dateString" : "03/01/2021" }

See MongoDB $dateToString for more information about this operator.

The $toString Operator

The $toString aggregation pipeline operator is similar to $dateToString, except that it can convert from various types – it’s not just limited to converting from a Date.

But for our purposes, we’re converting from a Date.

Example:

db.cats.aggregate(
   [
     {
       $project: {
         _id: 0,
          dateString: { $toString: "$born" }
       }
     }
   ]
)

Result:

{ "dateString" : "2021-01-03T23:30:15.123Z" }

This operator doesn’t give us the option of specifying a format, so the format is returned as is.

See MongoDB $toString 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: "string",
              onError: "An error occurred",
              onNull: "Input was null or empty" 
            }
          }
        }
    }
  ]
)

Result:

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

Notice 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.