The $dateFromString operator converts text date values into BSON Date objects inside aggregation pipelines. Use it when imports, APIs, or legacy systems store timestamps as strings and you need proper dates for sorting, indexing, or operators like $dateDiff and $dateAdd.
01
Parse Strings
Text → BSON Date.
02
Syntax
dateString field.
03
Format
ISO 8601 or custom.
04
Timezone
Optional Olson zone.
05
Error Handling
onError, onNull.
06
vs $convert
Parse vs generic cast.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $dateFromString operator parses a string into a BSON Date. For example, if a document stores createdAt: "2024-06-15T10:30:00Z" as text, $dateFromString can turn it into a real date value for range queries, chronological sorting, or elapsed-time calculations.
💡
Beginner Tip
$dateFromString returns a Date, not a string. When you omit format, MongoDB expects ISO 8601 (e.g. "2024-06-15" or "2024-06-15T10:30:00Z"). For other layouts like "06/15/2024", supply a matching format pattern.
Foundation
📝 Syntax
The $dateFromString operator takes an object with a required string and optional parsing options:
The format string must match the layout of dateString exactly. Use %H:%M:%S extensions when the string includes time components, e.g. format: "%m/%d/%Y %H:%M".
Example 3 — Parse with Timezone
When the string has no UTC offset, interpret it in a specific timezone:
mongosh
db.events.aggregate([
{
$project: {
title: 1,
localStartStr: 1,
startsAt: {
$dateFromString: {
dateString: "$localStartStr",
format: "%Y-%m-%d %H:%M",
timezone: "America/Chicago"
}
}
}
}
])
// localStartStr: "2024-07-04 09:00" in Central Time → UTC equivalent
How It Works
The timezone field tells MongoDB which Olson zone to use when the string lacks an explicit offset. This is important for daylight saving and regional event schedules.
Example 4 — Handle Invalid Dates with onError
During migration, some rows may have bad date text. Use onError and onNull instead of failing the pipeline:
onError catches parse failures; onNull handles missing values. Filter or flag bad rows in a follow-up stage rather than stopping the entire aggregation.
Applications
🚀 Use Cases
CSV and JSON imports — convert string date columns into BSON dates during ETL.
Third-party APIs — parse ISO or locale-specific date strings from webhook payloads.
Log analysis — turn text timestamps into dates for time-range filtering and bucketing.
Data cleanup — use onError to quarantine invalid rows without crashing the pipeline.
🧠 How $dateFromString Works
1
MongoDB reads dateString
dateString is evaluated per document — a field reference or literal text value.
Input
2
$dateFromString parses the text
MongoDB applies format (or ISO 8601 default) and optional timezone.
Parse
3
A BSON Date is returned
On failure, onError or onNull provides a fallback; otherwise an error is thrown.
Output
=
📅
A query-ready timestamp
Use with $match date ranges, $dateDiff, indexes, and any operator that expects a BSON Date.
Wrap Up
Conclusion
The $dateFromString operator is the standard way to turn text timestamps into BSON dates in MongoDB aggregation pipelines. It supports ISO 8601 out of the box and custom format patterns for legacy or locale-specific layouts.
Pair it with $dateFromParts when your data uses numeric components instead of strings, and use onError / onNull when importing messy data. After parsing, index the new date field and replace string columns when possible.
Store dates as BSON Date at insert time when you control the schema
Match format exactly to your string layout
Use onError and onNull during bulk imports
Prefer ISO 8601 strings when designing new APIs
Index the parsed date field after migration
❌ Don’t
Leave dates as strings if you query by date range often
Guess the format — mismatched patterns cause errors or wrong dates
Confuse $dateFromString with $dateToString (format out, not in)
Forget timezone when strings lack an offset
Assume all locales use the same date order (MM/DD vs DD/MM)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $dateFromString
Use these points when parsing date strings in MongoDB.
5
Core concepts
📅01
Parse Strings
Text → BSON Date.
Purpose
📝02
One Required
dateString.
Syntax
🛠03
ISO Default
Omit format for ISO.
Format
🌐04
Safe Imports
onError, onNull.
Option
⚠05
Not $dateToString
Parse vs format out.
Important
❓ Frequently Asked Questions
$dateFromString converts a date/time string into a BSON Date inside aggregation pipelines. Use it when dates are stored as text — for example from CSV imports, APIs, or legacy systems — and you need a real Date for sorting or date math.
{ $dateFromString: { dateString: <string>, format: <string>, timezone: <string>, onError: <expression>, onNull: <expression> } }. Only dateString is required. When format is omitted, MongoDB expects an ISO 8601 string.
$dateFromString parses a text value using a format pattern or ISO 8601. $dateFromParts builds a date from separate numeric fields like year, month, and day. Use the operator that matches how your data is stored.
onError returns a fallback value when parsing fails (bad format or invalid date). onNull returns a fallback when dateString is null or missing. Both prevent the entire pipeline from failing on messy data.
$dateFromString is available in MongoDB 3.6 and later in aggregation pipelines and update pipelines that use aggregation expressions.