$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

yearnumberrequired

The year component of the date.

monthnumberrequired

The month component of the date.

daynumberrequired

The day component of the date.

hournumber

The hour component of the date.

minutenumber

The minute component of the date.

secondnumber

The second component of the date.

millisecondnumber

The millisecond component of the date.

timezonestring

Optional. 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"
  }
]

Related