In MongoDB, the $toDate
aggregation operator converts a value to a date
$toDate
takes any valid expression. If the expression can’t be converted to a date, it returns an error. If the expression is null
or missing, it returns null
.
Example
Suppose we have a collection called samples
with the following document:
{ "_id" : ObjectId("60066f1cc8eb4369cf6ad9c9"), "double" : 1613372035500.75, "decimal" : NumberDecimal("1613372035500.75"), "long" : NumberLong("1613372035500"), "string" : "2021-02-15 06:53:55" }
We can use the following query to return each of those values as a Date.
db.samples.aggregate(
[
{
$project:
{
_id: 0,
"ObjectId": { $toDate: "$_id" },
"double": { $toDate: "$double" },
"decimal": { $toDate: "$decimal" },
"long": { $toDate: "$long" },
"string": { $toDate: "$string" }
}
}
]
).pretty()
Result:
{ "ObjectId" : ISODate("2021-01-19T05:33:16Z"), "double" : ISODate("2021-02-15T06:53:55.500Z"), "decimal" : ISODate("2021-02-15T06:53:55.500Z"), "long" : ISODate("2021-02-15T06:53:55.500Z"), "string" : ISODate("2021-02-15T06:53:55Z") }
As expected, all fields are returned with their corresponding values converted to Date values.
You may notice that the ObjectId field returns a different date to the others. This is because the _id
field’s value reflects the date that the document was created, whereas the other dates were just arbitrary dates created by me. More about the ObjectId below.
Input Types
The $toDate
operator accepts the following input types:
- Double
- Decimal
- Long
- String (must be a valid date string)
- ObjectId
More about these below.
Numeric Types
When using the numeric types (Double, Decimal, and Long), $toDate
returns a date that corresponds to the number of milliseconds represented by the value. For Double and Decimal, this is the truncated value. The $toDate
operator interprets numeric values as follows:
- A positive value corresponds to the number of milliseconds since Jan 1, 1970.
- A negative value corresponds to the number of milliseconds before Jan 1, 1970.
String Types
When using a string type, the string must be a valid date string. For example:
"2021-02-15"
"15 February 2021"
"2021-02-15 06:53:55"
"2021-02-15 06:53:55+1100"
You can’t use incomplete dates or invalid values such as "Monday"
, "March"
, "2020"
, etc.
ObjectId
ObjectId values are 12 byte hexadecimal values that consist of:
- A 4 byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
- A 5 byte is a random value
- A 3 byte incrementing counter, initialised to a random value.
The $toDate
operator returns the timestamp portion as a Date.