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