$dateFromParts (Construct Date from Parts)
Last updated: 2026-10-09
$dateFromParts (Construct Date from Parts)
$dateFromParts builds a date from numeric parts such as year, month, day, hour, minute, second, and millisecond — the inverse of $dateToParts. It has two modes: calendar fields (year, month, day...) or ISO 8601 week fields (isoWeekYear, isoWeek, isoDayOfWeek). Unspecified fields take their minimum (month defaults to 1, hour to 0). Useful for rebuilding dates from stored components or building range boundaries. timezone sets the resulting date's zone and defaults to UTC.
| Category | Date |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateFromParts: { year: <number>, month: <number>, day: <number>, hour: <number>, minute: <number>, second: <number>, millisecond: <number>, timezone: <timezone> } }
⚙️ Parameters
| year | Required; year in calendar mode, or isoWeekYear in ISO mode. |
|---|---|
| month / isoWeek | Month (default 1) or ISO week; use only the fields of one mode. |
| day / isoDayOfWeek | Day (default 1) or ISO day of week. |
| hour/minute/second/millisecond | Optional; default to 0. |
| timezone | Optional timezone for the constructed date. |
Returns:The constructed BSON Date; null if year is missing.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateFromParts: rebuild event time from parts (Beijing time)
db.events.aggregate([
{ $project: {
startedAt: { $dateFromParts: { year: '$y', month: '$m', day: '$d', timezone: 'Asia/Shanghai' } }
} }
])
Output:
{ "_id": 1, "startedAt": ISODate("2026-09-25T00:00:00Z") }
{ "_id": 2, "startedAt": ISODate("2026-10-01T00:00:00Z") }
📌 Notes
- ISO mode uses isoWeekYear/isoWeek/isoDayOfWeek; never mix with year/month/day
- Out-of-range values throw (e.g. month 13) — validate input first
- timezone affects the result; defaults to UTC
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan I build a date from year only?
AYes — month defaults to 1, day to 1, and time parts to 0.
QCan I mix calendar and ISO fields?
ANo — calendar and ISO fields are mutually exclusive; mixing throws.
QDo out-of-range values throw?
AYes, e.g. month 13 or day 32 throws — validate before passing.