MongoDB $dateFromString Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $dateFromString?

$dateFromString is a MongoDB aggregation expression that parses a date string into a BSON Date. Use it when dates arrive as text and you need a real date for sorting, filtering, or date math.

Remember
$dateFromString = text → BSON Date

{ $dateFromString: {
    dateString: <expression>,   // required
    format:     <string>,       // optional
    timezone:   <string>,       // optional
    onError:    <expression>,   // optional fallback
    onNull:     <expression>    // optional fallback
  }
}

no format → ISO-style parse when possible
bad string → error (unless onError is set)
null / missing → null (unless onNull is set)
UsePrefer
Parse a date stored as text$dateFromString
Build a date from year/month/day fields$dateFromParts
Date → formatted string$dateToString

How to Use $dateFromString in MongoDB

Point at the string field, add a format when the text is not ISO-like, then handle bad values if needed.

  1. Choose an expression stage ($addFields or $project).
  2. Set dateString to the field (or expression) that holds the text.
  3. Add format when the string is custom (for example "%d/%m/%Y").
  4. Optionally set onError / onNull so messy rows do not fail the pipeline.
PieceRequired?Role
dateStringYesText to parse
formatNoPattern when the string is not ISO-like
onError / onNullNoFallbacks for bad or missing text

Pseudocode

Pseudocode
for each document:
    s = evaluate(dateString)
    if s is null or missing:
        result = onNull if set, else null
    else:
        try:
            result = parse(s, format?, timezone?)
        catch:
            result = onError if set, else error  // pipeline fails
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while parsing date strings.

TopicDetail
TypeAggregation expression (not a find filter)
Minimal syntax{ $dateFromString: { dateString: "$when_text" } }
Custom formatformat: "%d/%m/%Y" for "02/10/2026"
Common specs%Y year, %m month, %d day
Safe parseonError: null keeps bad rows from failing
Round-trip pair$dateToString formats Date → text
Sample check"2026-10-02" → ISODate("2026-10-02T00:00:00Z")

Live Preview

Watch a date string become a BSON-style ISODate. Custom formats need a matching format pattern in MongoDB.

Simulates $dateFromString (same idea as the mongosh examples below).

Result
dateString = "2026-10-02T09:15:00Z"
format = (default / ISO-style)

$dateFromString → ISODate("2026-10-02T09:15:00.000Z")

{ event_date: ISODate("2026-10-02T09:15:00.000Z") }

Worked Walkthrough — ISO Date Text

One event stores the time as text: "2026-10-02T09:15:00Z". We want a real BSON Date.

Calculation
Document:
  { when_text: "2026-10-02T09:15:00Z" }

$dateFromString: { dateString: "$when_text" }

Step by step:
  1) Read the string field
  2) Parse as ISO-style date/time (UTC via Z)
  3) Store a BSON Date

Result:
  ISODate("2026-10-02T09:15:00.000Z")

Now you can sort, $match by range, or use date math.

MongoDB Examples

We store one event with two date strings: an ISO value and a day/month/year value. First we insert the data, then we parse each style. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one event with two text dates: an ISO timestamp and a day/month/year label. We save them in a collection named events.

mongosh
db.events.insertOne({
  _id: 1,
  title: "Launch",
  when_text: "2026-10-02T09:15:00Z",
  local_text: "02/10/2026"
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in events. Run find() to see it:

mongosh
db.events.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
title"Launch"Event name
when_text"2026-10-02T09:15:00Z"ISO-style date string
local_text"02/10/2026"Day/month/year text (needs a format)
Picture
Text in → Date out:

  when_text:  "2026-10-02T09:15:00Z"  → parse without format
  local_text: "02/10/2026"            → parse with "%d/%m/%Y"

Until you parse them, MongoDB treats both as plain strings
(so date-range queries and date math will not work as expected).

How It Works

  1. Insert once. insertOne adds a single event document to events.
  2. MongoDB stores fields as written. Both date fields are still strings, not Dates.
  3. find() shows the same shape. What you inserted is what you get back—ready for $dateFromString next.

Example 2 — Parse ISO Text

Goal: turn when_text into a real BSON Date using the default ISO-style parse.

mongosh
db.events.aggregate([
  {
    $addFields: {
      event_date: {
        $dateFromString: {
          dateString: "$when_text"
        }
      }
    }
  }
]);

How It Works

  1. Read the stored string. MongoDB already has when_text: "2026-10-02T09:15:00Z" from Example 1.
  2. Parse without a custom format. ISO-style strings are accepted when format is omitted.
  3. Get a BSON Date. The new field event_date is a real Date, not text.
  4. Keep all fields. $addFields adds event_date next to the original strings—nothing is deleted.

Example 3 — Custom Format

Same document, but parse local_text with an explicit format pattern.

mongosh
db.events.aggregate([
  {
    $addFields: {
      local_date: {
        $dateFromString: {
          dateString: "$local_text",
          format: "%d/%m/%Y"
        }
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using local_text: "02/10/2026" from Example 1.
  2. Match the pattern. %d/%m/%Y means day, month, year with slashes.
  3. Parse to midnight UTC. With no time in the string, the time part is 00:00:00.000Z.
  4. Easy check. Day 02, month 10, year 2026 → October 2, 2026.

Edge Cases & Pitfalls

Check these before using $dateFromString in production pipelines.

format

Custom text needs a matching format

Strings like "02/10/2026" are ambiguous. Set format (for example "%d/%m/%Y") so day and month are not swapped.

error

Bad strings can fail the pipeline

Without onError, a single unparseable value can stop the aggregation. Use onError: null (or another fallback) on messy imports.

tz

Do not mix Z with timezone

If the string already ends with Z (UTC), do not also pass timezone. Pick one source of truth for the zone.

null

Null and missing become null

Missing dateString returns null unless you set onNull. That is quieter than a parse error, but still not a Date.

Performance Notes

ApproachCostBest for
$dateFromString alonePer-document parseISO / simple date text fields
+ custom formatStill O(docs)Locale-style strings (d/m/Y, etc.)
+ onError / onNullTiny extra branchingDirty imports that must keep running

Parsing is cheap compared with large sorts or joins. If you reuse the Date often, consider converting once and storing a real Date field. Filter early with $match when only some rows need parsing.

Key Takeaways

  • Role: text date → BSON Date in aggregation.
  • ISO: often works with only dateString.
  • Custom: set format (for example "%d/%m/%Y").
  • Safety: use onError / onNull on messy data.

One line: $dateFromString answers “turn this date text into a real Date”—with optional format and safe fallbacks.

Frequently Asked Questions

$dateFromString converts a date/time string into a BSON Date inside aggregation. Use it when dates are stored as text—CSV imports, APIs, or legacy fields—and you need a real Date for sorting or date math.
Use { $dateFromString: { dateString: <expression>, format: <string>, timezone: <string>, onError: <expression>, onNull: <expression> } }. Only dateString is required. If format is omitted, MongoDB tries ISO-style parsing.
$dateFromString parses one text value. $dateFromParts builds a date from separate numeric fields like year, month, and day. Pick the operator that matches how your data is stored.
onError returns a fallback when parsing fails. onNull returns a fallback when dateString is null or missing. Without onError, a bad string can fail the whole pipeline.
%Y is year, %m month, %d day, %H hour, %M minute, %S second. Example: format "%d/%m/%Y" matches "02/10/2026".
Similar idea—text in, Date out—but MongoDB uses its own format rules and options. Run it in the aggregation pipeline, not as a standalone find() filter.

Next: $dateSubtract

Subtract days, hours, or other units from a date in aggregation.

$dateSubtract tutorial →

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.

9 people found this page helpful