Date Manipulation Tips
Essential Date Manipulation Techniques
1. Date Comparison and Filtering
## Find documents within a specific date range
db.logs.find({
timestamp: {
$gte: new Date("2023-01-01"),
$lt: new Date("2023-12-31")
}
})
Date Arithmetic Operations
Adding/Subtracting Time
## Add days to a timestamp
db.events.aggregate([
{
$addFields: {
futureDate: {
$dateAdd: {
startDate: "$timestamp",
unit: "day",
amount: 7
}
}
}
}
])
flowchart TD
A[Date Extraction] --> B[Year]
A --> C[Month]
A --> D[Day]
A --> E[Hour]
A --> F[Minute]
## Extract specific date components
db.users.aggregate([
{
$addFields: {
registrationYear: { $year: "$registrationDate" },
registrationMonth: { $month: "$registrationDate" },
registrationDay: { $dayOfMonth: "$registrationDate" }
}
}
])
Advanced Date Manipulation
Time Zone Conversion
## Convert timestamps to different time zones
db.events.aggregate([
{
$addFields: {
localTime: {
$dateFromParts: {
year: { $year: "$timestamp" },
month: { $month: "$timestamp" },
day: { $dayOfMonth: "$timestamp" },
hour: { $hour: "$timestamp" },
minute: { $minute: "$timestamp" },
timezone: "America/New_York"
}
}
}
}
])
Common Date Manipulation Patterns
Operation |
MongoDB Method |
Example Use Case |
Add Time |
$dateAdd |
Scheduling future events |
Subtract Time |
$dateSubtract |
Calculating duration |
Compare Dates |
$gt, $lt, $gte, $lte |
Filtering time-based records |
Extract Components |
$year, $month, $day |
Reporting and aggregation |
- Use indexed date fields for faster queries
- Minimize complex date transformations
- Leverage aggregation pipeline for efficient date operations
Error Handling Strategies
## Validate date before insertion
function validateDate(date) {
try {
return new Date(date);
} catch (error) {
return new Date(); // Fallback to current date
}
}
Note: When exploring date manipulation in LabEx MongoDB environments, always consider the specific requirements of your application and database design.