Concept Flow - Date expressions ($year, $month, $dayOfMonth)
Start with Date Field
Extract $year
Use extracted parts
Output Result
Extract year, month, and day from a date field step-by-step to use in queries or transformations.
db.orders.aggregate([
{ $project: {
year: { $year: "$orderDate" },
month: { $month: "$orderDate" },
day: { $dayOfMonth: "$orderDate" }
}}
])| Step | Document orderDate | $year | $month | $dayOfMonth | Output Document |
|---|---|---|---|---|---|
| 1 | 2023-06-15T10:30:00Z | 2023 | 6 | 15 | {"year": 2023, "month": 6, "day": 15} |
| 2 | 2022-12-01T08:00:00Z | 2022 | 12 | 1 | {"year": 2022, "month": 12, "day": 1} |
| 3 | 2024-01-31T23:59:59Z | 2024 | 1 | 31 | {"year": 2024, "month": 1, "day": 31} |
| 4 | 2023-11-07T00:00:00Z | 2023 | 11 | 7 | {"year": 2023, "month": 11, "day": 7} |
| 5 | 2023-06-15T10:30:00Z | 2023 | 6 | 15 | {"year": 2023, "month": 6, "day": 15} |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | Final |
|---|---|---|---|---|---|---|
| orderDate | N/A | 2023-06-15T10:30:00Z | 2022-12-01T08:00:00Z | 2024-01-31T23:59:59Z | 2023-11-07T00:00:00Z | Processed all |
| $year | N/A | 2023 | 2022 | 2024 | 2023 | Last value 2023 |
| $month | N/A | 6 | 12 | 1 | 11 | Last value 11 |
| $dayOfMonth | N/A | 15 | 1 | 31 | 7 | Last value 7 |
Date expressions extract parts from a date field. $year returns the year number (e.g., 2023). $month returns the month number (1-12). $dayOfMonth returns the day number (1-31). Use in aggregation $project to create new fields. Handles ISODate or date strings internally.
{$year: "$dateField"} return when used in an aggregation pipeline?$year operator$year expression extracts the year component from a date value.dateField{$year: "$dateField"} returns the year number from the date stored in dateField.$year extracts year [OK]createdAt in a MongoDB aggregation pipeline?$month, so the correct syntax is { $month: "$createdAt" }.dateField value of ISODate("2023-07-15T10:00:00Z")?
{ $project: { year: { $year: "$dateField" }, month: { $month: "$dateField" }, day: { $dayOfMonth: "$dateField" } } }orderDate:
{ $project: { day: { $dayOfMonth: orderDate } } }
But it throws an error. What is the mistake?$dayOfMonthorderDate without quotes and $ causes a syntax error in aggregation.saleDate field. Which aggregation pipeline stage correctly groups by year and month using date expressions?saleDate and summing amount is done correctly in { $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } }.Pass the test and this pattern moves unknown