Introduction to MongoDB $dateToString Operator

The MongoDB $dateToString operator is used to convert a date field to a string and format the date into a specified string format. The operator can be used in the aggregation pipeline to return formatted date strings in query results.

Syntax

The syntax of the MongoDB $dateToString operator is as follows:

{ $dateToString: { format: <formatString>, date: <dateExpression>, timezone: <tzExpression> } }

The parameters are:

  • format: Required. A string that specifies the format of the date field to be formatted. It must contain one or more format specifiers.
  • date: Optional. The date field to be formatted, which can be a date object or an expression that represents a date field.
  • timezone: Optional. A string that represents the time zone and is used to specify the time zone of the date to be formatted. By default, dates are formatted in the UTC time zone.

Use Cases

  • Format a date field into a specific string format for readability.
  • Group and sort results in the aggregation pipeline by the formatted date.
  • Convert a date field to a string for comparison with other data.

Examples

Example 1: Format a date as a string

Assume that we have a collection named orders that contains information about multiple orders, including the order number, order amount, and order time. Now, we need to convert the order time to a string in a specific format.

Assume that the orders collection contains the following documents:

{ "_id": 1, "order_no": "20220101001", "order_amount": 100, "order_time": ISODate("2022-01-01T10:30:00Z") }
{ "_id": 2, "order_no": "20220102001", "order_amount": 200, "order_time": ISODate("2022-01-02T14:45:00Z") }

We can use the following aggregation operation to format the order time as a string:

db.orders.aggregate([
  {
    $project: {
      order_no: 1,
      order_amount: 1,
      order_time: {
        $dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$order_time" }
      }
    }
  }
])

After executing the aggregation operation above, the following results will be returned:

{ "_id": 1, "order_no": "20220101001", "order_amount": 100, "order_time": "2022-01-01 10:30:00" }
{ "_id": 2, "order_no": "20220102001", "order_amount": 200, "order_time": "2022-01-02 14:45:00" }

Example 2: Format a date with timezone conversion

Assume that we have a collection named events that contains information about multiple events, including the event name, start time, and timezone. Now, we need to convert the start time of the event to another timezone and format it as a string.

Assume that the events collection contains the following documents:

{
  _id: 1,
  name: "Event 1",
  start_time: ISODate("2022-03-01T08:00:00Z"),
  timezone: "Asia/Shanghai"
}
{
  _id: 2,
  name: "Event 2",
  start_time: ISODate("2022-03-01T10:00:00Z"),
  timezone: "America/New_York"
}

We can use the $dateToString operator along with the $dateFromString and $convert operators to perform timezone conversion and date formatting.

db.events.aggregate([
  {
    $addFields: {
      converted_start_time: {
        $dateFromString: {
          dateString: {
            $dateToString: {
              date: {
                $dateFromString: {
                  dateString: "$start_time",
                  timezone: "$timezone"
                }
              },
              format: "%Y-%m-%d %H:%M:%S",
              timezone: "America/New_York"
            }
          },
          timezone: "America/New_York"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      converted_start_time: 1
    }
  }
])

The above aggregation operation will produce the following result:

{
  name: 'Event 1',
  converted_start_time: ISODate('2022-03-01T00:00:00Z')
}
{
  name: 'Event 2',
  converted_start_time: ISODate('2022-03-01T10:00:00Z')
}

In the above aggregation operation, the $dateFromString operator is first used to convert the start_time field to a date object and the $convert operator is used to convert it to the dateString type. Next, the $dateToString operator is used to format the dateString as a string in the specified format and convert it to a date object in the target timezone. Finally, the $addFields operator is used to add the converted date object as a new field called converted_start_time and the $project operator is used to output the specified fields.

Conclusion

In this example, we demonstrated how to use the $dateToString operator along with the $dateFromString and $convert operators to perform timezone conversion and date formatting. The $dateToString operator can flexibly convert date objects to strings in the specified format and support timezone conversion. By combining with other operators, more complex date operations can be achieved.