- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $toDate (aggregation)
$toDate (aggregation)¶
On this page
Definition¶
-
$toDate
¶ New in version 4.0.
Converts a value to a date. If the value cannot be converted to a date,
$toDate
errors. If the value is null or missing,$toDate
returns null.$toDate
has the following syntax:The
$toDate
takes any valid expression.The
$toDate
is a shorthand for the following$convert
expression:See also
Behavior¶
The following table lists the input types that can be converted to a date:
Input Type | Behavior |
---|---|
Double | Returns a date that corresponds to the number of milliseconds represented by the truncated double value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
Decimal | Returns a date that corresponds to the number of milliseconds represented by the truncated decimal value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
Long | Returns a date that corresponds to the number of milliseconds represented by the long value. Positive number corresponds to the number of milliseconds since Jan 1, 1970. Negative number corresponds to the number of milliseconds before Jan 1, 1970. |
String | Returns a date that corresponds to the date string. The string must be a valid date string, such as:
|
ObjectId | Returns a date that corresponds to the timestamp of the ObjectId. |
The following table lists some conversion to date examples:
Example | Results |
---|---|
{$toDate: 120000000000.5} |
ISODate(“1973-10-20T21:20:00Z”) |
{$toDate: NumberDecimal("1253372036000.50")} |
ISODate(“2009-09-19T14:53:56Z”) |
{$toDate: NumberLong("1100000000000")} |
ISODate(“2004-11-09T11:33:20Z”) |
{$toDate: NumberLong("-1100000000000")} |
ISODate(“1935-02-22T12:26:40Z”) |
{$toDate: ObjectId("5ab9c3da31c2ab715d421285")} |
ISODate(“2018-03-27T04:08:58Z”) |
{$toDate: "2018-03-03"} |
ISODate(“2018-03-03T00:00:00Z”) |
{$toDate: "2018-03-20 11:00:06 +0500"} |
ISODate(“2018-03-20T06:00:06Z”) |
{$toDate: "Friday"} |
Error |
Example¶
Create a collection orders
with the following documents:
The following aggregation operation on the orders
collection
converts the order_date
to date before sorting by the date value:
The operation returns the following documents:
Note
If the conversion operation encounters an error, the aggregation
operation stops and throws an error. To override this behavior, use
$convert
instead.