Date Operations
Date Comparison Operators
MongoDB provides powerful operators for comparing and manipulating dates:
graph LR
A[Date Comparison Operators] --> B[$gt Greater Than]
A --> C[$lt Less Than]
A --> D[$gte Greater Than or Equal]
A --> E[$lte Less Than or Equal]
Basic Comparison Examples
- Finding records after a specific date:
## Find events after June 1, 2023
db.events.find({
eventDate: { $gt: new Date("2023-06-01") }
})
- Finding records within a date range:
## Find events between two dates
db.events.find({
eventDate: {
$gte: new Date("2023-06-01"),
$lte: new Date("2023-12-31")
}
})
Date Manipulation Techniques
Operator |
Description |
Example |
$year |
Extract year |
{ $year: "$dateField" } |
$month |
Extract month |
{ $month: "$dateField" } |
$dayOfMonth |
Extract day |
{ $dayOfMonth: "$dateField" } |
$hour |
Extract hour |
{ $hour: "$dateField" } |
Aggregation Example:
db.orders.aggregate([
{
$project: {
year: { $year: "$orderDate" },
month: { $month: "$orderDate" },
totalSales: 1
}
}
])
Advanced Date Calculations
- Adding/Subtracting Time:
## Add 7 days to a date
db.events.find({
futureDate: {
$eq: new Date(originalDate.getTime() + 7*24*60*60*1000)
}
})
- Date Difference Calculation:
db.orders.aggregate([
{
$project: {
daysSinceOrder: {
$divide: [
{ $subtract: [new Date(), "$orderDate"] },
1000 * 60 * 60 * 24
]
}
}
}
])
Time Zone Handling
graph TD
A[Date Operations] --> B[UTC Conversion]
A --> C[Local Time Handling]
A --> D[Time Zone Awareness]
Time Zone Conversion:
## Convert to specific time zone
db.events.aggregate([
{
$project: {
localTime: {
$dateToString: {
format: "%Y-%m-%d %H:%M:%S",
date: "$eventDate",
timezone: "America/New_York"
}
}
}
}
])
LabEx Insight
When mastering MongoDB date operations, LabEx provides comprehensive practice environments to explore these advanced techniques interactively.
- Index date fields for faster queries
- Use native MongoDB date operators
- Minimize complex date calculations in queries