$dateToString (Format Date)

Last updated: 2026-10-09

$dateToString (Format Date)

$dateToString formats a date into a string using a format pattern — the standard way to output dates in aggregation pipelines. The pattern uses placeholders like %Y (year), %m (month), %d (day), %H (hour), similar to strftime. When date is null/missing it returns null unless onNull provides a default.

CategoryDate
MongoDB Version3.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateToString: { format: <format>, date: <date-expression>, timezone: <timezone>, onNull: <default> } }

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $dateToString: format order dates
db.orders.aggregate([
  { $project: {
      dateStr: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
  } }
])

Output:

{ "_id": 1, "dateStr": "2026-09-25" }
{ "_id": 2, "dateStr": "2026-09-24" }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow do I specify a timezone?
AUse IANA names (e.g. "Asia/Shanghai") or UTC offsets (e.g. "+08:00"). Defaults to UTC.
QWhich format specifiers does $dateToString support?
ACommon ones include %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second), %L (millisecond), %z (UTC offset) and %j (day of year). See the official docs for the full list.
QWhat happens if the date field is not a Date?
AIt expects a Date; otherwise it returns null or errors (depending on strict mode). Convert with $toDate first if needed.
QCan it output ISO 8601 format?
AYes. Combine %Y-%m-%dT%H:%M:%S.%LZ to produce something like 2026-10-01T08:30:00.000Z; alternatively use the $isoDate expression.
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%

🙏 帮我们做得更好

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

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