Bird
Raised Fist0
MongoDBquery~20 mins

Date expressions ($year, $month, $dayOfMonth) in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Extract the year from a date field
Given a MongoDB collection events with documents containing a date field, which aggregation pipeline stage correctly extracts the year from the date field into a new field called year?
MongoDB
db.events.aggregate([
  { $project: { year: ??? } }
])
A{ year: { $year: "$date" } }
B{ year: { $dayOfMonth: "$date" } }
C{ year: { $month: "$date" } }
D{ year: { $dateToString: { format: "%Y", date: "$date" } } }
Attempts:
2 left
💡 Hint
Use the $year operator to get the year part of a date.
❓ query_result
intermediate
2:00remaining
Find documents from a specific month
You want to find all documents in the orders collection where the orderDate is in March (month 3). Which aggregation pipeline stage filters documents correctly?
MongoDB
db.orders.aggregate([
  { $match: { ??? } }
])
A{ $expr: { $eq: [ { $month: "$orderDate" }, 3 ] } }
B{ orderDate: { $eq: 3 } }
C{ $expr: { $eq: [ { $dayOfMonth: "$orderDate" }, 3 ] } }
D{ orderDate: { $month: 3 } }
Attempts:
2 left
💡 Hint
Use $expr to compare the month part of the date.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in date extraction
Which option contains a syntax error when trying to extract the day of the month from a createdAt field in an aggregation pipeline?
MongoDB
db.users.aggregate([
  { $project: { day: ??? } }
])
A} } "tAdetaerc$" :htnoMfOyad$ { :yad {
B{ day: { $dayOfMonth: ["$createdAt"] } }
C{ day: { $dayOfMonth: "$createdAt" } }
D{ day: { $dayOfMonth: createdAt } }
Attempts:
2 left
💡 Hint
Field names must be strings with $ prefix inside quotes.
🧠 Conceptual
advanced
2:00remaining
Understanding output types of date expressions
What is the data type of the value returned by the MongoDB $year, $month, and $dayOfMonth expressions when used in an aggregation pipeline?
ADate object representing the extracted part
BString representing the year, month, or day
CInteger number representing the year, month, or day
DBoolean indicating if the date part exists
Attempts:
2 left
💡 Hint
Think about what kind of value you get when you ask for a year or month number.
❓ query_result
expert
3:00remaining
Combine $year, $month, and $dayOfMonth to format a date string
You want to create a new field formattedDate in the format YYYY-MM-DD using $year, $month, and $dayOfMonth from a timestamp field. Which aggregation pipeline stage produces the correct string format with leading zeros for month and day?
MongoDB
db.logs.aggregate([
  { $project: { formattedDate: ??? } }
])
A
{ $concat: [
  { $toString: { $year: "$timestamp" } }, "-",
  { $toString: { $month: "$timestamp" } }, "-",
  { $toString: { $dayOfMonth: "$timestamp" } }
] }
B
{ $concat: [
  { $toString: { $year: "$timestamp" } }, "-",
  { $cond: [ { $lt: [ { $month: "$timestamp" }, 10 ] }, { $concat: ["0", { $toString: { $month: "$timestamp" } }] }, { $toString: { $month: "$timestamp" } } ] }, "-",
  { $cond: [ { $lt: [ { $dayOfMonth: "$timestamp" }, 10 ] }, { $concat: ["0", { $toString: { $dayOfMonth: "$timestamp" } }] }, { $toString: { $dayOfMonth: "$timestamp" } } ] }
] }
C{ $dateToString: { format: "%Y-%m-%d", date: "$timestamp" } }
D
{ $concat: [
  { $year: "$timestamp" }, "-",
  { $month: "$timestamp" }, "-",
  { $dayOfMonth: "$timestamp" }
] }
Attempts:
2 left
💡 Hint
You need to add leading zeros for month and day if less than 10.

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