- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $dateToString (aggregation)
$dateToString (aggregation)¶
On this page
Definition¶
-
$dateToString¶ Converts a date object to a string according to a user-specified format.
The
$dateToStringexpression has the following operator expression syntax:The
$dateToStringtakes a document with the following fields:Field Description dateChanged in version 3.6.
The date to convert to string.
<dateExpression>must be a valid expression that resolves to a Date, a Timestamp, or an ObjectID.formatOptional. The date format specification.
<formatString>can be any string literal, containing 0 or more format specifiers. For a list of specifiers available, see Format Specifiers.If unspecified,
$dateToStringuses"%Y-%m-%dT%H:%M:%S.%LZ"as the default format.Changed in version 4.0: The
formatfield is optional iffeatureCompatibilityVersion(fCV) is set to"4.0"or greater. For more information on fCV, seesetFeatureCompatibilityVersion.timezoneOptional.The timezone of the operation result.<tzExpression>must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If notimezoneis provided, the result is displayed inUTC.Format Examples Olson Timezone IdentifierUTC OffsetonNullOptional. The value to return if the
dateis null or missing. The arguments can be any valid expression.If unspecified,
$dateToStringreturns null if thedateis null or missing.New in version 4.0: Requires
featureCompatibilityVersion(fCV) set to"4.0"or greater. For more information on fCV, seesetFeatureCompatibilityVersion.
Format Specifiers¶
The following format specifiers are available for use in the
<formatString>:
| Specifiers | Description | Possible Values |
|---|---|---|
%d |
Day of Month (2 digits, zero padded) | 01-31 |
%G |
Year in ISO 8601 format | 0000-9999 |
%H |
Hour (2 digits, zero padded, 24-hour clock) | 00-23 |
%j |
Day of year (3 digits, zero padded) | 001-366 |
%L |
Millisecond (3 digits, zero padded) | 000-999 |
%m |
Month (2 digits, zero padded) | 01-12 |
%M |
Minute (2 digits, zero padded) | 00-59 |
%S |
Second (2 digits, zero padded) | 00-60 |
%w |
Day of week (1-Sunday, 7-Saturday) | 1-7 |
%u |
Day of week number in ISO 8601 format (1-Monday, 7-Sunday) | 1-7 |
%U |
Week of year (2 digits, zero padded) | 00-53 |
%V |
Week of Year in ISO 8601 format | 01-53 |
%Y |
Year (4 digits, zero padded) | 0000-9999 |
%z |
The timezone offset from UTC. | +/-[hh][mm] |
%Z |
The minutes offset from UTC as a number. For example, if the
timezone offset (+/-[hhmm]) was +0445, the minutes
offset is +285. |
+/-mmm |
%% |
Percent Character as a Literal | % |
Example¶
Consider a sales collection with the following document:
The following aggregation uses $dateToString to
return the date field as formatted strings:
The operation returns the following result: