Extract Year, Month, and Day from Dates in MongoDB
📖 Scenario: You work at a small online store. The store keeps records of orders in a MongoDB collection called orders. Each order has a date field that stores when the order was placed.You want to create a new collection that shows the year, month, and day of each order separately. This helps the store analyze sales by date parts.
🎯 Goal: Create a MongoDB aggregation pipeline that extracts the year, month, and dayOfMonth from the date field of each order document.Store the results in a new collection called order_dates.
📋 What You'll Learn
Create an orders collection with three documents, each having a date field with exact ISODate values.
Define a variable pipeline that holds the aggregation pipeline array.
Use $year, $month, and $dayOfMonth expressions in the $project stage to extract date parts.
Use db.orders.aggregate(pipeline) to run the pipeline and db.order_dates.insertMany() to save the results.
💡 Why This Matters
🌍 Real World
Extracting parts of dates is common in sales, event tracking, and reporting systems to analyze data by year, month, or day.
💼 Career
Database developers and analysts often write aggregation pipelines to transform and summarize date data for business insights.
Progress0 / 4 steps
1
Create the orders collection with date data
Create a collection called orders with exactly these three documents, each having a date field with the given ISODate values: { _id: 1, date: ISODate("2023-01-15T10:00:00Z") }, { _id: 2, date: ISODate("2023-06-20T15:30:00Z") }, { _id: 3, date: ISODate("2023-12-05T08:45:00Z") }
MongoDB
Hint
Use db.orders.insertMany() with an array of objects. Each object must have _id and date fields.
2
Define the aggregation pipeline variable
Create a variable called pipeline and set it to an array with one $project stage. For now, leave the $project stage empty (an empty object {}).
MongoDB
Hint
Use const pipeline = [ { $project: { } } ] to create the pipeline variable.
3
Extract year, month, and day using date expressions
Update the $project stage inside the pipeline variable to include these fields: - year using $year on $date - month using $month on $date - day using $dayOfMonth on $date
Run the aggregation and save results to order_dates
Run the aggregation pipeline on orders using db.orders.aggregate(pipeline).toArray() and insert the results into a new collection called order_dates using db.order_dates.insertMany().
MongoDB
Hint
Use const results = db.orders.aggregate(pipeline).toArray() and then db.order_dates.insertMany(results).
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
Step 1: Understand the $year operator
The $year expression extracts the year component from a date value.
Step 2: Apply to the field dateField
Using {$year: "$dateField"} returns the year number from the date stored in dateField.
Final Answer:
The year part of the date stored in dateField -> Option B
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
Step 1: Identify correct field reference syntax
In MongoDB aggregation, field names must be referenced as strings with a $ prefix, like "$createdAt".
Step 2: Confirm correct operator usage
The operator to extract month is $month, so the correct syntax is { $month: "$createdAt" }.
Final Answer:
{ $month: "$createdAt" } -> Option A
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")?
Step 1: Extract year, month, and day from the date
The date is July 15, 2023. So, year = 2023, month = 7 (July), day = 15.
Step 2: Confirm output matches extracted values
The output document will have year: 2023, month: 7, day: 15 as projected.
Final Answer:
{ year: 2023, month: 7, day: 15 } -> Option C
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
Step 1: Check field reference syntax inside $dayOfMonth
Field names must be referenced as strings with a $ prefix, so it should be "$orderDate".
Step 2: Identify the cause of error
Using orderDate without quotes and $ causes a syntax error in aggregation.
Final Answer:
Missing quotes and $ before field name in $dayOfMonth -> Option A
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?