0
0
MongoDBquery~30 mins

Date expressions ($year, $month, $dayOfMonth) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
MongoDB
Need a hint?

Use { year: { $year: "$date" }, month: { $month: "$date" }, day: { $dayOfMonth: "$date" } } inside $project.

4
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
Need a hint?

Use const results = db.orders.aggregate(pipeline).toArray() and then db.order_dates.insertMany(results).