Date expressions help you get parts of a date like the year, month, or day from a date stored in your database. This makes it easy to organize or filter data by date.
0
0
Date expressions ($year, $month, $dayOfMonth) in MongoDB
Introduction
You want to find all records from a specific year, like sales in 2023.
You need to group data by month to see monthly trends.
You want to filter events that happened on a certain day of the month.
You are creating reports that show data by year, month, or day.
You want to sort data based on the year or month part of a date.
Syntax
MongoDB
{ $year: <dateExpression> }
{ $month: <dateExpression> }
{ $dayOfMonth: <dateExpression> }<dateExpression> is the date field or expression you want to extract parts from.
These expressions return numbers: year (e.g., 2024), month (1-12), day of month (1-31).
Examples
Extracts the year from the
orderDate field.MongoDB
{ $year: "$orderDate" }Gets the month number from the
createdAt date.MongoDB
{ $month: "$createdAt" }Finds the day of the month from the
eventDate field.MongoDB
{ $dayOfMonth: "$eventDate" }Sample Program
This query takes the orderDate from each order and creates new fields showing the year, month, and day of that date. It also keeps the item field to see what was ordered.
MongoDB
db.orders.aggregate([
{
$project: {
year: { $year: "$orderDate" },
month: { $month: "$orderDate" },
day: { $dayOfMonth: "$orderDate" },
item: 1
}
}
])OutputSuccess
Important Notes
If the date field is missing or null, these expressions return null.
Months are numbered 1 for January through 12 for December.
Use these expressions inside aggregation pipelines like $project or $group.
Summary
Use $year, $month, and $dayOfMonth to get parts of a date.
They help organize and filter data by date parts easily.
These expressions work inside MongoDB aggregation pipelines.