$dateToParts
Used to extract individual components (Year, Month, Day, Hour, Minute, Second, Millisecond, etc.) from a date object. The operator is useful for scenarios where manipulation or analysis of specific date parts is required, such as sorting, filtering, or aggregating data based on individual date components.
Syntax
$dateToParts: { date: <dateExpression>, timezone: <string>, iso8601: <boolean> }
Parameters
date
objectrequiredThe date expression to extract parts from.
timezone
stringOptional. Specifies the timezone for the date. Defaults to UTC if not provided.
iso8601
objectOptional. If true, the operator uses ISO 8601 week date calendar system. Defaults to false.
Examples
Extracting date parts from a field
This query uses $dateToParts to break down the lastUpdated date into components like year, month, day, and time. It helps in analyzing or transforming individual parts of a date for further processing.
Query:
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
dateParts: {
$dateToParts: {
date: "$lastUpdated"
}
}
}
}
])
Output:
[
{
"dateParts": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 11,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]
Using timezone
This query extracts the lastUpdated timestamp of a specific document and breaks it into date parts like year, month, day, and hour using $dateToParts. Including the "America/New_York" timezone permits the breakdown, reflects the local time instead of UTC.
Query:
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
datePartsWithTimezone: {
$dateToParts: {
date: "$lastUpdated",
timezone: "America/New_York"
}
}
}
}
])
Output:
[
{
"datePartsWithTimezone": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 6,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]