$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.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $toDate: <expression> }

⚙️ Parameters

expressionA 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏