$toDate (Convert to Date)
Last updated: 2026-10-09
$toDate (Convert to Date)
$toDate converts a value to a BSON Date. It passes dates through, treats numbers as millisecond timestamps, and parses ISO 8601 strings. Typical uses: converting log time strings into dates for day-level grouping or standardizing millisecond timestamps from frontends. Invalid strings throw, so prefer $convert with onError for dirty data. Null input yields null. Compared with $dateFromString, $toDate has simpler syntax and auto-detects ISO formats.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toDate: <expression> }
⚙️ Parameters
| expression | A date, a numeric millisecond timestamp, or an ISO string. |
|---|
Returns:A Date; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toDate: parse a time string into a date
db.logs.aggregate([
{ $project: {
ts: { $toDate: '$timeStr' }
} }
])
Output:
{ '_id': 1, 'ts': { '$date': '2026-09-25T08:00:00Z' } }
📌 Notes
- Numbers are millisecond timestamps; second-level timestamps need a multiply by 1000 first
- Non-ISO strings (e.g. '2026/09/25') throw
- null input yields null
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhich strings can it parse?
AISO 8601 formats, e.g. '2026-09-25T08:00:00Z'.
QWhat about second-level timestamps?
AMultiply by 1000 first: { $multiply: ['$ts', 1000] }, then convert.
QHow does it differ from $dateFromString?
A$toDate auto-detects ISO formats; $dateFromString customizes format and timezone.