Bird
Raised Fist0
MongoDBquery~10 mins

Date expressions ($year, $month, $dayOfMonth) in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
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.
Execution Sample
MongoDB
db.orders.aggregate([
  { $project: {
      year: { $year: "$orderDate" },
      month: { $month: "$orderDate" },
      day: { $dayOfMonth: "$orderDate" }
  }}
])
This query extracts the year, month, and day from the orderDate field of each document.
Execution Table
StepDocument orderDate$year$month$dayOfMonthOutput Document
12023-06-15T10:30:00Z2023615{"year": 2023, "month": 6, "day": 15}
22022-12-01T08:00:00Z2022121{"year": 2022, "month": 12, "day": 1}
32024-01-31T23:59:59Z2024131{"year": 2024, "month": 1, "day": 31}
42023-11-07T00:00:00Z2023117{"year": 2023, "month": 11, "day": 7}
52023-06-15T10:30:00Z2023615{"year": 2023, "month": 6, "day": 15}
💡 All documents processed, date parts extracted for each.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
orderDateN/A2023-06-15T10:30:00Z2022-12-01T08:00:00Z2024-01-31T23:59:59Z2023-11-07T00:00:00ZProcessed all
$yearN/A2023202220242023Last value 2023
$monthN/A612111Last value 11
$dayOfMonthN/A151317Last value 7
Key Moments - 3 Insights
Why does $month return 6 for June instead of 5?
$month returns the calendar month number starting at 1 for January, so June is 6. See execution_table rows 1 and 5 where $month is 6 for June dates.
What happens if the date field is missing or null?
If the date field is missing or null, $year, $month, and $dayOfMonth return null or no value. This is not shown in the current table but is important to handle in real queries.
Are the extracted values numbers or strings?
The extracted values are numbers, as shown in the output documents in execution_table rows, e.g., "year": 2023 is a number.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the $dayOfMonth value at Step 3?
A7
B31
C1
D15
💡 Hint
Check the $dayOfMonth column in execution_table row with Step 3.
At which step does $month equal 12?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the $month column in execution_table and find where it is 12.
If the orderDate was missing in a document, what would $year return?
ACurrent year
B0
CNull or no value
DError stops query
💡 Hint
Refer to key_moments about missing or null date fields.
Concept Snapshot
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.
Full Transcript
This visual execution trace shows how MongoDB date expressions $year, $month, and $dayOfMonth extract parts from a date field in documents. Each step processes one document's orderDate, extracting year, month, and day as numbers. The execution table lists each document's date and the extracted values. The variable tracker shows how these values change per document. Key moments clarify common confusions like month numbering starting at 1, handling missing dates, and data types of extracted parts. The quiz tests understanding of these values at specific steps and behavior with missing dates. The snapshot summarizes usage and behavior of these date expressions in MongoDB aggregation pipelines.

Practice

(1/5)
1. What does the MongoDB expression {$year: "$dateField"} return when used in an aggregation pipeline?
easy
A. The month number of the date
B. The year part of the date stored in dateField
C. The full date as a string
D. The day of the week of the date

Solution

  1. Step 1: Understand the $year operator

    The $year expression extracts the year component from a date value.
  2. Step 2: Apply to the field dateField

    Using {$year: "$dateField"} returns the year number from the date stored in dateField.
  3. Final Answer:

    The year part of the date stored in dateField -> Option B
  4. Quick Check:

    $year extracts year [OK]
Hint: Remember $year extracts only the year number from a date [OK]
Common Mistakes:
  • Confusing $year with $month or $dayOfMonth
  • Expecting a full date string instead of just the year
  • Using $year outside aggregation pipeline
2. Which of the following is the correct syntax to extract the month from a date field named createdAt in a MongoDB aggregation pipeline?
easy
A. { $month: "$createdAt" }
B. { $month: createdAt }
C. { month: "$createdAt" }
D. { $month: "createdAt" }

Solution

  1. Step 1: Identify correct field reference syntax

    In MongoDB aggregation, field names must be referenced as strings with a $ prefix, like "$createdAt".
  2. Step 2: Confirm correct operator usage

    The operator to extract month is $month, so the correct syntax is { $month: "$createdAt" }.
  3. Final Answer:

    { $month: "$createdAt" } -> Option A
  4. Quick Check:

    Field names need "$" prefix in aggregation [OK]
Hint: Use "$fieldName" to reference fields inside aggregation [OK]
Common Mistakes:
  • Omitting quotes and $ prefix around field name
  • Using operator without $ sign
  • Passing field name as plain string without $
3. Given the following aggregation stage, what will be the output for a document with dateField value of ISODate("2023-07-15T10:00:00Z")?
{ $project: { year: { $year: "$dateField" }, month: { $month: "$dateField" }, day: { $dayOfMonth: "$dateField" } } }
medium
A. { year: 2023, month: 7, day: 14 }
B. { year: 2023, month: 6, day: 15 }
C. { year: 2023, month: 7, day: 15 }
D. { year: 2022, month: 7, day: 15 }

Solution

  1. Step 1: Extract year, month, and day from the date

    The date is July 15, 2023. So, year = 2023, month = 7 (July), day = 15.
  2. Step 2: Confirm output matches extracted values

    The output document will have year: 2023, month: 7, day: 15 as projected.
  3. Final Answer:

    { year: 2023, month: 7, day: 15 } -> Option C
  4. Quick Check:

    Date parts match output [OK]
Hint: Remember months are 1-based in MongoDB date expressions [OK]
Common Mistakes:
  • Assuming months start at 0 instead of 1
  • Confusing dayOfMonth with dayOfWeek
  • Misreading the date value
4. You wrote this aggregation stage to get the day of the month from orderDate:
{ $project: { day: { $dayOfMonth: orderDate } } }
But it throws an error. What is the mistake?
medium
A. Missing quotes and $ before field name in $dayOfMonth
B. Using $project instead of $match
C. Field orderDate is not a date type
D. Incorrect operator; should use $day instead

Solution

  1. Step 1: Check field reference syntax inside $dayOfMonth

    Field names must be referenced as strings with a $ prefix, so it should be "$orderDate".
  2. Step 2: Identify the cause of error

    Using orderDate without quotes and $ causes a syntax error in aggregation.
  3. Final Answer:

    Missing quotes and $ before field name in $dayOfMonth -> Option A
  4. Quick Check:

    Field names need "$" prefix in aggregation [OK]
Hint: Always use "$fieldName" inside aggregation expressions [OK]
Common Mistakes:
  • Forgetting $ and quotes around field names
  • Assuming $day is a valid operator
  • Confusing aggregation stages
5. You want to group sales documents by the year and month of their saleDate field. Which aggregation pipeline stage correctly groups by year and month using date expressions?
hard
A. { $group: { _id: { year: { $year: "$saleDate" }, month: "$month" }, totalSales: { $sum: "$amount" } } }
B. { $group: { _id: { year: "$year", month: "$month" }, totalSales: { $sum: "$amount" } } }
C. { $group: { _id: { year: { $year: saleDate }, month: { $month: saleDate } }, totalSales: { $sum: "$amount" } } }
D. { $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } }

Solution

  1. Step 1: Use correct field references with $year and $month

    Field names must be referenced as strings with $ prefix, so "$saleDate" is correct.
  2. Step 2: Verify grouping keys and sum operator

    Grouping by year and month extracted from saleDate and summing amount is done correctly in { $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } }.
  3. Final Answer:

    { $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } } -> Option D
  4. Quick Check:

    Correct field references and operators used [OK]
Hint: Group by {_id: {year: {$year: "$field"}, month: {$month: "$field"}}} [OK]
Common Mistakes:
  • Using field names without $ and quotes
  • Mixing string field names with expressions
  • Incorrectly mixing aggregation operators
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard