$dateFromString (Parse String to Date)

Last updated: 2026-10-09

$dateFromString (Parse String to Date)

$dateFromString parses a string into a date using a given format — the inverse of $dateToString, handy for converting imported or front-end date strings into BSON Dates. format uses the same placeholders as $dateToString (%Y, %m, %d...); without it, ISO 8601 is assumed. onError supplies a fallback when parsing fails, onNull when input is null. timezone decides which zone applies when the string carries no zone info.

CategoryDate
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateFromString: { dateString: <string>, format: <format>, timezone: <timezone>, onError: <default>, onNull: <default> } }

⚙️ Parameters

dateStringRequired; the date string to parse.
formatOptional format pattern; defaults to ISO 8601.
timezoneOptional timezone applied when the string lacks zone info.
onError / onNullOptional fallbacks for parse failure and null input.

Returns:The parsed BSON Date; onError on failure (throws by default), onNull for null input (null by default).

▶ Example

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

// $dateFromString: parse imported log timestamps (Beijing time)
 db.imports.aggregate([
  { $project: {
      createdAt: { $dateFromString: { dateString: '$ts', format: '%Y-%m-%d %H:%M', timezone: 'Asia/Shanghai' } }
  } }
])

Output:

{ "_id": 1, "createdAt": ISODate("2026-09-25T08:30:00Z") }
{ "_id": 2, "createdAt": ISODate("2026-09-25T09:00:00Z") }

📌 Notes

📚 Related Tutorials

❓ FAQ

QHow to parse strings with varying formats?
AWithout format, ISO 8601 is tried; when the format is fixed, pass format explicitly.
QDoes parse failure throw?
AYes, unless onError supplies a fallback.
QHow is this different from $toDate?
A$toDate is a loose type conversion; $dateFromString controls format and timezone precisely.
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%

🙏 帮我们做得更好

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

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