MongoDB $dateFromParts Operator

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

What You’ll Learn

The $dateFromParts operator assembles a BSON Date from separate numeric fields such as year, month, and day. Use it when legacy data stores date components in different columns, or when you need to build a timestamp inside an aggregation pipeline without string parsing.

01

Build Dates

Parts → BSON Date.

02

Syntax

year, month, day.

03

Time Parts

hour, minute, second.

04

Timezone

Optional Olson zone.

05

Use Cases

Legacy data, ETL.

06

vs $dateToParts

Build vs split.

Definition and Usage

In MongoDB’s aggregation framework, the $dateFromParts operator constructs a single BSON Date from integer components. For example, if a document stores birthYear: 1995, birthMonth: 8, and birthDay: 15, $dateFromParts can combine them into one date value for sorting, filtering, or further date math with operators like $dateAdd or $dateDiff.

💡
Beginner Tip

$dateFromParts returns a Date, not a number. At minimum you must supply year, month, and day. Omitted time fields default to midnight (00:00:00.000). Requires MongoDB 5.0+.

📝 Syntax

The $dateFromParts operator takes an object with date and optional time fields:

mongosh
{
  $dateFromParts: {
    year: <intExpression>,
    month: <intExpression>,
    day: <intExpression>,
    hour: <intExpression>,
    minute: <intExpression>,
    second: <intExpression>,
    millisecond: <intExpression>,
    timezone: <stringExpression>
  }
}

Syntax Rules

  • year, month, day — required; use 1–12 for month and valid day for the given month.
  • hour, minute, second, millisecond — optional; default to 0.
  • timezone — optional Olson timezone ID (e.g. "UTC", "America/Chicago").
  • Alternative ISO week fields: isoWeekYear, isoWeek, isoDayOfWeek instead of calendar year/month/day.
  • Returns a BSON Date stored in UTC internally.

💡 $dateFromParts vs $dateToParts vs $dateFromString

$dateFromParts — numeric components → BSON Date
$dateToParts — BSON Date → numeric components (inverse)
$dateFromString — formatted date string → BSON Date

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date)
Required fieldsyear, month, day
Return typeBSON Date
Default time00:00:00.000 when hour/minute/second omitted
MongoDB version5.0+
Basic date
{
  $dateFromParts: {
    year: 2024,
    month: 6,
    day: 15
  }
}

June 15, 2024 at midnight UTC

From fields
{
  $dateFromParts: {
    year: "$y",
    month: "$m",
    day: "$d"
  }
}

Combine document fields

With time
{
  $dateFromParts: {
    year: 2024,
    month: 1,
    day: 1,
    hour: 14,
    minute: 30
  }
}

Include hour and minute

With timezone
{
  $dateFromParts: {
    year: 2024,
    month: 7,
    day: 4,
    hour: 9,
    timezone: "America/New_York"
  }
}

Local time in a zone

Examples Gallery

Build dates from separate fields, add time components, construct timezone-aware timestamps, and normalize legacy imports with $dateFromParts.

📚 Build a Date from Document Fields

Use a users collection where birth date parts are stored as separate integers.

Sample Input Documents

Suppose you have a users collection with year, month, and day stored separately:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "name": "Alice",
    "birthYear": 1995,
    "birthMonth": 8,
    "birthDay": 15
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "name": "Bob",
    "birthYear": 2001,
    "birthMonth": 3,
    "birthDay": 22
  }
]

Example 1 — Combine Parts into birthDate

Construct a single birthDate field from the three integer fields:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      birthYear: 1,
      birthMonth: 1,
      birthDay: 1,
      birthDate: {
        $dateFromParts: {
          year: "$birthYear",
          month: "$birthMonth",
          day: "$birthDay"
        }
      }
    }
  }
])

How It Works

  • MongoDB reads each field per document and assembles a valid calendar date.
  • Omitted time parts default to midnight UTC.
  • The result is a BSON Date you can sort, compare, or pass to $dateDiff.

📈 Practical Patterns

Add time of day, respect timezones, and migrate legacy CSV-style data.

Example 2 — Include Hour and Minute

Build an appointment timestamp when date and time are stored as separate numbers:

mongosh
db.appointments.aggregate([
  {
    $project: {
      patient: 1,
      scheduledAt: {
        $dateFromParts: {
          year: "$apptYear",
          month: "$apptMonth",
          day: "$apptDay",
          hour: "$apptHour",
          minute: "$apptMinute"
        }
      }
    }
  }
])

// apptYear: 2024, apptMonth: 6, apptDay: 10, apptHour: 14, apptMinute: 30
// → ISODate("2024-06-10T14:30:00.000Z")

How It Works

Each time component is optional beyond the required date parts. Use second and millisecond when you need finer precision for logging or event ordering.

Example 3 — Timezone-Aware Construction

Interpret local date/time in a specific timezone before storing as UTC:

mongosh
db.events.aggregate([
  {
    $project: {
      title: 1,
      startsAt: {
        $dateFromParts: {
          year: 2024,
          month: 7,
          day: 4,
          hour: 9,
          minute: 0,
          timezone: "America/New_York"
        }
      }
    }
  }
])

// 9:00 AM Eastern on July 4, 2024 → stored as UTC equivalent

How It Works

Without timezone, parts are treated as UTC. With an Olson ID, MongoDB interprets the components in that zone, which matters for daylight saving and regional reporting.

Example 4 — Normalize Legacy Import Data

During ETL, replace separate date columns with a proper Date field and drop the old parts:

mongosh
db.legacy_orders.aggregate([
  {
    $set: {
      orderDate: {
        $dateFromParts: {
          year: "$orderYear",
          month: "$orderMonth",
          day: "$orderDay"
        }
      }
    }
  },
  {
    $unset: ["orderYear", "orderMonth", "orderDay"]
  }
])

How It Works

Use $set (or $addFields) to create the normalized date, then $unset redundant fields. After migration, index orderDate for efficient range queries.

🚀 Use Cases

  • Legacy databases — combine year/month/day columns from old relational imports into BSON dates.
  • Form submissions — merge separate dropdown values (day, month, year) into one timestamp at write time.
  • Reporting pipelines — construct period start/end dates from integer parameters in $facet or dashboard queries.
  • Inverse of $dateToParts — round-trip date decomposition and reconstruction for custom calendars.

🧠 How $dateFromParts Works

1

MongoDB evaluates each part

year, month, day, and optional time fields are resolved per document — literals or field references.

Input
2

$dateFromParts assembles the calendar

MongoDB validates the combination and applies timezone if provided.

Construct
3

A BSON Date is returned

The result is stored in the field you define — ready for sorting, indexing, or date math.

Output
=

One unified timestamp

Use with $dateDiff, $dateAdd, $match on date ranges, or export to applications expecting ISO dates.

Conclusion

The $dateFromParts operator is the clearest way to build BSON dates from numeric components in MongoDB aggregation pipelines. It avoids fragile string concatenation and manual parsing when your data already stores year, month, and day as separate values.

Pair it with $dateToParts when you need to split dates back into components, or $dateFromString when your source is a formatted string. Always validate that month and day values are sensible, and ensure your MongoDB deployment is version 5.0 or later.

💡 Best Practices

✅ Do

  • Validate year, month, and day at insert time when possible
  • Use timezone when local calendar semantics matter
  • Index the resulting Date field after normalization
  • Prefer $dateFromParts over string concat + $dateFromString for numeric parts
  • Combine with $dateDiff once you have a proper BSON date

❌ Don’t

  • Use $dateFromParts on MongoDB versions before 5.0
  • Pass month as zero — use 1–12 (January = 1)
  • Assume invalid dates roll over silently — bad combos can error
  • Confuse $dateFromParts with $dateToParts
  • Forget timezone when building “local midnight” dates

Key Takeaways

Knowledge Unlocked

Five things to remember about $dateFromParts

Use these points when constructing dates from components in MongoDB.

5
Core concepts
📝 02

Three Required

year, month, day.

Syntax
🛠 03

Date Output

Not a number.

Output
🌐 04

Timezone

Optional Olson ID.

Option
05

Not $dateToParts

Build vs split.

Important

❓ Frequently Asked Questions

$dateFromParts builds a BSON Date from separate numeric components such as year, month, and day. It is useful when dates are stored as individual fields instead of a single Date value.
{ $dateFromParts: { year: <int>, month: <int>, day: <int>, hour: <int>, minute: <int>, second: <int>, millisecond: <int>, timezone: <string> } }. year, month, and day are required; time parts default to zero.
ISODate() is a shell helper for literal date strings. $dateFromParts is an aggregation expression that constructs dates from document fields at query time inside pipelines.
Yes. Pass an optional timezone field with an Olson timezone ID such as "America/New_York" or "UTC". The date is interpreted in that zone before conversion to UTC storage.
$dateFromParts is available in MongoDB 5.0 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $dateFromString to parse formatted date strings, or review $dateDiff to measure time between dates.

Next: $dateFromString →

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