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.