MongoDB $dateFromString Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

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.

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.

📝 Syntax

The $dateFromString operator takes an object with a required string and optional parsing options:

mongosh
{
  $dateFromString: {
    dateString: <stringExpression>,
    format: <stringExpression>,
    timezone: <stringExpression>,
    onError: <expression>,
    onNull: <expression>
  }
}

Syntax Rules

  • dateString — required; the text value to parse (field reference or literal).
  • format — optional; pattern using format specifiers like %Y (year), %m (month), %d (day). Omit for ISO 8601.
  • timezone — optional Olson timezone ID when the string has no offset.
  • onError — optional fallback when parsing fails (invalid format or date).
  • onNull — optional fallback when dateString is null or missing.
  • Returns a BSON Date stored in UTC internally.

Common Format Specifiers

  • %Y — four-digit year (2024)
  • %m — month 01–12
  • %d — day 01–31
  • %H — hour 00–23
  • %M — minute 00–59
  • %S — second 00–60
  • %L — millisecond 000–999

💡 $dateFromString vs $dateFromParts vs $convert

$dateFromString — formatted date string → BSON Date
$dateFromParts — numeric year/month/day fields → BSON Date
$convert — generic type cast with to: "date"; less control over format

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date)
Required fieldsdateString
Return typeBSON Date
Default parsingISO 8601 when format is omitted
MongoDB version3.6+
ISO 8601
{
  $dateFromString: {
    dateString: "2024-06-15T10:30:00Z"
  }
}

No format needed

From field
{
  $dateFromString: {
    dateString: "$createdAtStr"
  }
}

Parse a document field

Custom format
{
  $dateFromString: {
    dateString: "06/15/2024",
    format: "%m/%d/%Y"
  }
}

US-style date string

Safe parse
{
  $dateFromString: {
    dateString: "$rawDate",
    onError: null,
    onNull: null
  }
}

Null on bad input

Examples Gallery

Parse ISO strings, handle US date formats, add timezone context, and safely migrate messy import data with $dateFromString.

📚 Parse ISO 8601 Date Strings

Use a logs collection where timestamps were imported as ISO text.

Sample Input Documents

Suppose you have a logs collection with string timestamps:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "event": "login",
    "timestampStr": "2024-06-15T10:30:00Z"
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "event": "logout",
    "timestampStr": "2024-06-16T18:45:00Z"
  }
]

Example 1 — Convert ISO String to timestamp

Parse the string field into a BSON Date without specifying a format:

mongosh
db.logs.aggregate([
  {
    $project: {
      event: 1,
      timestampStr: 1,
      timestamp: {
        $dateFromString: {
          dateString: "$timestampStr"
        }
      }
    }
  }
])

How It Works

  • When format is omitted, MongoDB parses standard ISO 8601 strings.
  • The Z suffix means UTC; the result is stored as a BSON Date.
  • You can now sort by timestamp or use $dateDiff for elapsed time.

📈 Practical Patterns

Custom formats, timezone interpretation, and safe parsing for messy data.

Example 2 — Parse a Custom Date Format

Handle US-style dates like "06/15/2024" with an explicit format pattern:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      orderDateStr: 1,
      orderDate: {
        $dateFromString: {
          dateString: "$orderDateStr",
          format: "%m/%d/%Y"
        }
      }
    }
  }
])

// orderDateStr: "06/15/2024" → ISODate("2024-06-15T00:00:00.000Z")

How It Works

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:

mongosh
db.imports.aggregate([
  {
    $project: {
      name: 1,
      rawDate: 1,
      parsedDate: {
        $dateFromString: {
          dateString: "$rawDate",
          format: "%d-%b-%Y",
          onError: null,
          onNull: null
        }
      }
    }
  },
  {
    $match: {
      parsedDate: { $ne: null }
    }
  }
])

// "15-Jun-2024" → valid Date; "not-a-date" → null (filtered out)

How It Works

onError catches parse failures; onNull handles missing values. Filter or flag bad rows in a follow-up stage rather than stopping the entire aggregation.

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

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.

💡 Best Practices

✅ Do

  • 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)

Key Takeaways

Knowledge Unlocked

Five things to remember about $dateFromString

Use these points when parsing date strings in MongoDB.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $dateSubtract to shift dates backward, or review $dateFromParts when your data uses numeric components.

Next: $dateSubtract →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful