Date Query Techniques
Date Comparison Operators
Basic Comparison Queries
## Find documents with dates after a specific point
db.events.find({
eventDate: { $gt: new Date("2023-01-01") }
})
## Find documents within a date range
db.events.find({
eventDate: {
$gte: new Date("2023-01-01"),
$lt: new Date("2023-12-31")
}
})
Date Range Queries
Operator Breakdown
Operator |
Meaning |
Example |
$gt |
Greater Than |
{ date: { $gt: date } } |
$gte |
Greater Than or Equal |
{ date: { $gte: date } } |
$lt |
Less Than |
{ date: { $lt: date } } |
$lte |
Less Than or Equal |
{ date: { $lte: date } } |
Advanced Date Querying
graph LR
A[Original Date] --> B[Extraction Method]
B --> C[Specific Date Component]
## Extract specific date components
db.collection.aggregate([
{
$project: {
year: { $year: "$createdAt" },
month: { $month: "$createdAt" },
day: { $dayOfMonth: "$createdAt" }
}
}
])
Complex Date Filtering
Time-Based Aggregations
## Find documents from last 30 days
db.logs.aggregate([
{
$match: {
timestamp: {
$gte: new Date(new Date().setDate(new Date().getDate() - 30))
}
}
}
])
Indexing Date Fields
graph TD
A[Date Field] --> B[Create Index]
B --> C[Faster Queries]
B --> D[Improved Performance]
## Create an index on date field
db.collection.createIndex({ createdAt: 1 })
Common Query Patterns
Pattern |
Description |
Use Case |
Recent Records |
Fetch last X days |
Reporting |
Future Events |
Find upcoming events |
Scheduling |
Historical Data |
Retrieve past records |
Analytics |
Best Practices
- Use appropriate date comparison operators
- Create indexes on date fields
- Be mindful of time zone considerations
- Leverage aggregation framework for complex date operations
Note: When exploring date query techniques in LabEx MongoDB environments, always test and optimize your queries for performance.