$dateToParts (Split Date into Parts)
Last updated: 2026-10-09
$dateToParts (Split Date into Parts)
$dateToParts splits a date into a document of year, month, day, hour, minute, second, and millisecond — the inverse of $dateFromParts. Set iso8601 to true to instead get isoWeekYear, isoWeek, and isoDayOfWeek. Common uses: group stats by year/month (as $group _id) or export dates as readable documents. timezone drives the split and defaults to UTC — always set it for cross-zone reporting.
| Category | Date |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateToParts: { date: <date-expression>, timezone: <timezone>, iso8601: <boolean> } }
⚙️ Parameters
| date | Required; the date expression to split. |
|---|---|
| timezone | Optional timezone; defaults to UTC. |
| iso8601 | Optional; true outputs ISO week-calendar fields. |
Returns:A document with year/month/day/hour/minute/second/millisecond (or ISO fields); null if date is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateToParts: split order time into parts (Beijing time)
db.orders.aggregate([
{ $project: { parts: { $dateToParts: { date: '$createdAt', timezone: 'Asia/Shanghai' } } } }
])
Output:
{ "_id": 1, "parts": { "year": 2026, "month": 9, "day": 25, "hour": 8, "minute": 30, "second": 0, "millisecond": 0 } }
📌 Notes
- Keys are fixed: year, month, day, hour, minute, second, millisecond
- With iso8601: true the keys become isoWeekYear, isoWeek, isoDayOfWeek
- Defaults to UTC — always set timezone for cross-zone stats
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat are the output field names?
AFixed keys: year, month, day, hour, minute, second, millisecond.
QHow to group stats by month?
ASplit with $dateToParts, then $group with _id as a year/month combination.
QWhat does iso8601 do?
AWhen true, outputs ISO week-calendar fields for week-based stats.