MongoDB $dateFromParts Operator

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

What Is $dateFromParts?

$dateFromParts is a MongoDB aggregation expression that builds a Date from separate numbers: year, month, day, and optional hour/minute/second. Use it when a document stores date pieces as fields instead of one Date.

Remember
$dateFromParts = Date from { year, month, day, ... }

{
  $dateFromParts: {
    year: <n>,          // required
    month: <n>,         // default 1
    day: <n>,           // default 1
    hour: <n>,          // default 0
    minute: <n>,        // default 0
    second: <n>,        // default 0
    millisecond: <n>,   // default 0
    timezone: "<tz>"    // optional
  }
}

inverse → $dateToParts
UsePrefer
Numbers → Date$dateFromParts
Date → numbers$dateToParts
String → Date$dateFromString

How to Use $dateFromParts in MongoDB

Point each part at a field (or literal), then emit one Date.

  1. Choose an expression stage ($addFields or $project).
  2. Set at least year (add month and day for a full calendar date).
  3. Optionally set time parts and timezone.
  4. Use the resulting Date with filters, sorts, or other date operators.
PieceRequired?Role
yearYesCalendar year
month / dayNoDefault to 1 if omitted
Time partsNoDefault to 0
timezoneNoInterpret parts in a named zone

Pseudocode

Pseudocode
for each document:
    y = evaluate(year)
    m = evaluate(month) or 1
    d = evaluate(day) or 1
    h, mi, s, ms = time parts or 0
    if year is null or missing:
        result = null
    else:
        result = Date(y, m, d, h, mi, s, ms)  // + timezone if set
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while building dates from parts.

TopicDetail
TypeAggregation expression (not a find filter)
Minimum{ year: <n> }
Defaultsmonth/day → 1; time → 0
Inverse$dateToParts
String inputUse $dateFromString instead
ISO weeksAlso supports isoWeekYear / isoWeek / isoDayOfWeek
Sample check2026, 1, 10 → 2026-01-10T00:00:00Z

Live Preview

Watch $dateFromParts turn year/month/day (and time) into one Date.

Simulates { $dateFromParts: { year, month, day, ... } } in UTC.

Result
year = 2026, month = 1, day = 10
$dateFromParts → 2026-01-10T00:00:00.000Z

Worked Walkthrough — Event Date

An event stores year 2026, month 1, and day 10 as separate numbers. We want one Date field.

Calculation
Document:
  { year: 2026, month: 1, day: 10 }

$dateFromParts:
  year  = 2026
  month = 1
  day   = 10
  (time defaults to 00:00:00.000)

Result → 2026-01-10T00:00:00.000Z ✓

MongoDB Examples

We use one event with numeric date parts. First build a date-only value, then include hour and minute. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one launch event stored as separate numbers: year 2026, month 1, day 10, hour 9, minute 30. We save them in a collection named events.

mongosh
db.events.insertOne({
  _id: 1,
  title: "Launch day",
  year: 2026,
  month: 1,
  day: 10,
  hour: 9,
  minute: 30
});

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 day"Event name
year / month / day2026 / 1 / 10Calendar date pieces
hour / minute9 / 30Time pieces (for Example 3)
Picture
Parts                 Date

year  2026  ┐
month    1  ├─→  2026-01-10T00:00:00Z
day     10  ┘

+ hour 9, minute 30
  →  2026-01-10T09:30:00Z

How It Works

  1. Insert once. insertOne adds a single event document to events.
  2. Parts are plain numbers. Nothing is a Date yet—just integers.
  3. find() shows the same shape. Ready for $dateFromParts next.

Example 2 — Year / Month / Day

Goal: build eventDate from year, month, and day (midnight UTC).

mongosh
db.events.aggregate([
  {
    $addFields: {
      eventDate: {
        $dateFromParts: {
          year: "$year",
          month: "$month",
          day: "$day"
        }
      }
    }
  }
]);

How It Works

  1. Read the three fields. year, month, and day come from Example 1.
  2. Assemble one Date. Time parts are omitted, so they default to 0 (midnight).
  3. Keep originals. $addFields adds eventDate next to the numeric parts.

Example 3 — With Hour and Minute

Same event, but include hour and minute for a timed Date.

mongosh
db.events.aggregate([
  {
    $addFields: {
      eventAt: {
        $dateFromParts: {
          year: "$year",
          month: "$month",
          day: "$day",
          hour: "$hour",
          minute: "$minute"
        }
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using the launch parts from Example 1.
  2. Add time fields. hour: 9 and minute: 30 set the clock.
  3. Easy check. Result is 2026-01-10T09:30:00Z.

Edge Cases & Pitfalls

Check these before using $dateFromParts in production pipelines.

year

Year is required

Without year, the expression fails. Month and day can be omitted (they default to 1).

overflow

Out-of-range parts normalize

Values like month 13 roll into the next year. Validate ranges if you want strict calendar dates.

string

Have a string? Use $dateFromString

$dateFromString parses text. $dateFromParts expects numbers.

tz

Timezone changes interpretation

Parts are interpreted in the given zone before storage as UTC. Set timezone when local wall time matters.

Performance Notes

ApproachCostBest for
$dateFromParts per documentCheap constructionLegacy schemas with split date fields
Build then $matchCompute on scanned docsFilter after assembling a Date
Store a real Date on writeNo rebuild on readHot queries that need Date indexes

Building a Date is cheap. Filter early with $match when only some documents need assembly.

Key Takeaways

  • Role: numbers → one Date.
  • Required: year; month/day default to 1.
  • Time: hour/minute/second default to 0.
  • Inverse: $dateToParts; strings → $dateFromString.

One line: $dateFromParts assembles a Date from year/month/day (and optional time) fields.

Frequently Asked Questions

$dateFromParts builds a BSON Date from separate numeric parts such as year, month, and day. Use it inside aggregation stages when dates are stored as individual fields.
Use { $dateFromParts: { year: <n>, month: <n>, day: <n>, hour: <n>, minute: <n>, second: <n>, millisecond: <n>, timezone: <tz> } }. year is required; month and day default to 1; time parts default to 0.
$dateFromParts builds a date from numeric fields. $dateFromString parses a date string with a format pattern.
$dateToParts splits a Date into year, month, day, and other parts.
Yes. Pass timezone with an Olson ID such as "America/New_York" or "UTC" when the parts should be interpreted in that zone.
MongoDB normalizes overflowing parts (for example month 13 becomes the next year). Prefer valid ranges so results stay easy to reason about.

Next: $dateFromString

Parse date strings into BSON Dates in an aggregation pipeline.

$dateFromString 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