$dateToString

Used to convert a date object to a string in a specified format. It's commonly used in aggregation pipelines to format date fields for reporting, querying, or display purposes. This operator is highly versatile and allows you to define custom date formats.

Syntax

$dateToString: { format: <format_string>, date: <date_expression>, timezone: <timezone>, onNull: <replacement_value> }

Parameters

formatstringrequired

A string that specifies the format of the output date.

dateobjectrequired

The date expression to format.

timezonestring

Optional. A string that specifies the timezone. Defaults to UTC if not provided.

onNullobject

Optional. A value to return if the date field is null or missing.

Examples

Formatting a date field to an ISO-like string

This query uses $dateToString operator to format the lastUpdated timestamp into a YYYY-MM-DD string. It helps present dates in a readable format suitable for logs, reports, or UI.

Query:

db.stores.aggregate([
  {
    $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
  },
  {
    $project: {
      _id: 0,
      formattedDate: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$lastUpdated"
        }
      }
    }
  }
])

Output:

[
  {
    "formattedDate": "2024-12-04"
  }
]

Handling Null Values

This query formats the nonexistent field lastUpdated_new timestamp as a YYYY-MM-DD string using $dateToString. Considering the date is missing or null, it substitutes a fallback string "No date available" via the onNull option.

Query:

db.stores.aggregate([
  {
    $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
  },
  {
    $project: {
      _id: 0,
      formattedDateOrDefault: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$lastUpdated_new",
          onNull: "No date available"
        }
      }
    }
  }
])

Output:

[
  {
    "formattedDateOrDefault": "No date available"
  }
]

Related