$dateFromParts
Constructs a date from individual components such as year, month, day, hour, minute, second, and millisecond. This operator can be useful when dealing with data that stores date components separately.
Syntax
$dateFromParts: { year: <year>, month: <month>, day: <day>, hour: <hour>, minute: <minute>, second: <second>, millisecond: <millisecond>, timezone: <timezone> }
Parameters
year
numberrequiredThe year component of the date.
month
numberrequiredThe month component of the date.
day
numberrequiredThe day component of the date.
hour
numberThe hour component of the date.
minute
numberThe minute component of the date.
second
numberThe second component of the date.
millisecond
numberThe millisecond component of the date.
timezone
stringOptional. A timezone specification.
Examples
Constructing a start date
This query constructs precise startDate and endDate values from nested fields using $dateFromParts, then calculates the event duration in days. It helps standardize and analyze event timelines stored in fragmented date formats.
Query:
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$unwind: "$promotionEvents"
},
{
$project: {
_id: 1,
startDate: {
$dateFromParts: {
year: "$promotionEvents.promotionalDates.startDate.Year",
month: "$promotionEvents.promotionalDates.startDate.Month",
day: "$promotionEvents.promotionalDates.startDate.Day"
}
}
}
}
])
Output:
[
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"startDate": "2024-09-21T00:00:00.000Z"
}
]