MongoDB $dateToParts Operator

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

What You’ll Learn

The $dateToParts operator decomposes a BSON Date into numeric parts such as year, month, day, hour, minute, second, and millisecond. Use it for dashboards, grouping by calendar month, birthday matching (ignoring year), or feeding values into $dateFromParts.

01

Split Dates

Date → parts object.

02

Syntax

date field required.

03

Components

year, month, day, time.

04

Timezone

Local calendar parts.

05

Use Cases

Reports, grouping.

06

vs $dateFromParts

Split vs build.

Definition and Usage

In MongoDB’s aggregation framework, the $dateToParts operator takes a single BSON Date and returns a document of integer components. For example, ISODate("2024-06-15T14:30:00Z") becomes { year: 2024, month: 6, day: 15, hour: 14, minute: 30, second: 0, millisecond: 0 } (in UTC unless you specify a timezone).

💡
Beginner Tip

$dateToParts returns an object, not a single number. Access fields with dot notation in later stages, e.g. $dateParts.year. Requires MongoDB 5.0+.

📝 Syntax

The $dateToParts operator takes an object with a required date and optional options:

mongosh
{
  $dateToParts: {
    date: <dateExpression>,
    timezone: <stringExpression>,
    iso8601: <booleanExpression>
  }
}

Syntax Rules

  • date — required; the BSON date to decompose (field, $$NOW, or literal).
  • timezone — optional Olson timezone ID; parts reflect that zone instead of UTC.
  • iso8601 — optional boolean; when true, also returns isoWeekYear, isoWeek, and isoDayOfWeek.
  • Default output fields: year, month (1–12), day, hour, minute, second, millisecond.
  • Month is 1-based (January = 1), matching calendar conventions and $dateFromParts.

💡 $dateToParts vs $dateFromParts vs $dateToString

$dateToParts — BSON Date → numeric components (object)
$dateFromParts — numeric components → BSON Date
$dateToString — BSON Date → formatted text string

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date)
Required fieldsdate
Return typeDocument of integer parts
Month range1–12 (January = 1)
MongoDB version5.0+
Basic split
{
  $dateToParts: {
    date: "$createdAt"
  }
}

UTC components

Get year only
{
  orderYear: {
    $getField: {
      field: "year",
      input: {
        $dateToParts: {
          date: "$orderDate"
        }
      }
    }
  }
}

Extract one part

With timezone
{
  $dateToParts: {
    date: "$eventAt",
    timezone: "America/New_York"
  }
}

Local calendar parts

ISO week parts
{
  $dateToParts: {
    date: "$loggedAt",
    iso8601: true
  }
}

isoWeekYear, isoWeek

Examples Gallery

Extract calendar parts from timestamps, report in local timezones, group sales by month, and use ISO week fields with $dateToParts.

📚 Split a Date into Components

Use an orders collection and extract year, month, and day from orderDate.

Sample Input Documents

Suppose you have an orders collection with BSON date fields:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "item": "Laptop",
    "orderDate": ISODate("2024-06-15T14:30:00Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "item": "Mouse",
    "orderDate": ISODate("2024-03-22T09:15:00Z")
  }
]

Example 1 — Extract dateParts from orderDate

Store the full parts object and flatten selected fields in $project:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      orderDate: 1,
      dateParts: {
        $dateToParts: { date: "$orderDate" }
      }
    }
  },
  {
    $project: {
      item: 1,
      orderYear: "$dateParts.year",
      orderMonth: "$dateParts.month",
      orderDay: "$dateParts.day"
    }
  }
])

How It Works

  • $dateToParts returns all time components in one object.
  • By default, parts are in UTC unless you pass timezone.
  • Flatten with a second $project or use dot notation in $group keys.

📈 Practical Patterns

Local timezone reporting, monthly aggregation, and ISO week analytics.

Example 2 — Parts in a Local Timezone

Extract calendar day as it appears in Eastern Time for regional dashboards:

mongosh
db.events.aggregate([
  {
    $project: {
      title: 1,
      eventAt: 1,
      localParts: {
        $dateToParts: {
          date: "$eventAt",
          timezone: "America/New_York"
        }
      }
    }
  },
  {
    $project: {
      title: 1,
      localYear: "$localParts.year",
      localMonth: "$localParts.month",
      localDay: "$localParts.day",
      localHour: "$localParts.hour"
    }
  }
])

How It Works

The same UTC instant can fall on different calendar days in different zones. Always set timezone when business reports use local dates rather than server UTC.

Example 3 — Group Sales by Year and Month

Use $dateToParts inside $group to bucket revenue by calendar month:

mongosh
db.orders.aggregate([
  {
    $addFields: {
      parts: { $dateToParts: { date: "$orderDate" } }
    }
  },
  {
    $group: {
      _id: {
        year: "$parts.year",
        month: "$parts.month"
      },
      totalSales: { $sum: "$amount" },
      orderCount: { $sum: 1 }
    }
  },
  { $sort: { "_id.year": 1, "_id.month": 1 } }
])

How It Works

Grouping on year and month from $dateToParts is cleaner than string formatting for analytics. Pair with $dateFromParts if you need month start/end boundaries.

Example 4 — ISO Week Fields for Reporting

Enable iso8601: true to get ISO week year and week number:

mongosh
db.logs.aggregate([
  {
    $project: {
      message: 1,
      loggedAt: 1,
      isoParts: {
        $dateToParts: {
          date: "$loggedAt",
          iso8601: true
        }
      }
    }
  },
  {
    $project: {
      message: 1,
      isoWeekYear: "$isoParts.isoWeekYear",
      isoWeek: "$isoParts.isoWeek",
      isoDayOfWeek: "$isoParts.isoDayOfWeek"
    }
  }
])

How It Works

ISO week fields follow the ISO 8601 calendar (week 1 contains the first Thursday of the year). Use them for weekly KPIs that must align with international week numbering.

🚀 Use Cases

  • Monthly and yearly reports — group or filter by extracted year and month.
  • Birthday reminders — match on month and day while ignoring year.
  • Timezone-aware dashboards — show local calendar parts to regional users.
  • Data transformation — split dates before writing separate columns or calling $dateFromParts.

🧠 How $dateToParts Works

1

MongoDB resolves the input date

date is evaluated per document — a field, $$NOW, or literal ISODate.

Input
2

$dateToParts decomposes the timestamp

MongoDB applies timezone and optional iso8601, then extracts calendar parts.

Split
3

A parts object is returned

Integer fields like year and month are ready for projection, grouping, or matching.

Output
=

Structured date components

Use in $group, $match, charts, or round-trip with $dateFromParts for custom date logic.

Conclusion

The $dateToParts operator is the standard way to break BSON dates into numeric components in MongoDB aggregation pipelines. It powers calendar-based grouping, local timezone reporting, and structured date transforms without string parsing.

Pair it with $dateFromParts when you need to rebuild dates from parts, or $dateToString when you need human-readable formatted output. Always specify timezone when reports must reflect local calendar days.

💡 Best Practices

✅ Do

  • Use timezone for local calendar reporting
  • Group on year and month for clean monthly analytics
  • Remember month is 1–12, matching $dateFromParts
  • Use iso8601: true when ISO week numbering is required
  • Store BSON dates at insert time; split at query time when needed

❌ Don’t

  • Use $dateToParts on MongoDB versions before 5.0
  • Confuse $dateToParts with $dateFromParts
  • Assume UTC parts match local business dates without timezone
  • Expect a single number — the result is always an object
  • Parse strings with $dateToParts — convert with $dateFromString first

Key Takeaways

Knowledge Unlocked

Five things to remember about $dateToParts

Use these points when splitting dates into components in MongoDB.

5
Core concepts
📝 02

One Required

date field.

Syntax
🛠 03

Object Output

year, month, day…

Output
🌐 04

Timezone

Local calendar parts.

Option
05

Not $dateFromParts

Split vs build.

Important

❓ Frequently Asked Questions

$dateToParts breaks a BSON Date into numeric components such as year, month, day, hour, minute, second, and millisecond. Use it for reporting, grouping by calendar parts, or preparing data for $dateFromParts.
{ $dateToParts: { date: <dateExpression>, timezone: <string>, iso8601: <boolean> } }. Only date is required. The operator returns a document of integer parts, not a single number.
$dateToParts splits one BSON Date into components. $dateFromParts assembles components into one BSON Date. They are inverse operations in the date operator family.
When you pass an Olson timezone ID such as "America/New_York", MongoDB extracts parts as they appear in that zone — useful for local calendar reporting instead of raw UTC values.
$dateToParts 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 $dateToString to format dates as text, or review $dateFromParts to rebuild dates from components.

Next: $dateToString →

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