$toDate
The `$toDate` operator converts a specified value into a date type.
Syntax
{
$toDate: <expression>
}
Parameters
expression
objectrequiredAn expression that can be converted to a date. Supported formats include: ISO date strings, milliseconds since Unix epoch (number), ObjectId, and Timestamp.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"lastUpdated": { "t": 1729983325, "i": 1 }
}
Convert timestamp to date
Convert the lastUpdated field from Unix timestamp to date format.
This query converts a timestamp to an ISO date.
Query:
db.stores.aggregate([{
$match: { _id: "905d1939-e03a-413e-a9c4-221f74055aac" }
}, {
$project: {
name: 1,
lastUpdated: 1,
lastUpdatedAsDate: { $toDate: "$lastUpdated" }
}
}])
Output:
[
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot",
"lastUpdated": { "t": 1729983325, "i": 1 },
"lastUpdatedAsDate": "ISODate('2024-10-26T22:55:25.000Z')"
}
]