MongoDB Query to Find Documents by Date Range
{ dateField: { $gte: ISODate("start_date"), $lte: ISODate("end_date") } } to find documents where the date is between the start and end dates inclusive.Examples
How to Think About It
$gte for 'greater than or equal' and $lte for 'less than or equal' to compare dates stored in ISODate format.Algorithm
Code
db.collection.find({
dateField: {
$gte: ISODate("2023-01-01T00:00:00Z"),
$lte: ISODate("2023-01-31T23:59:59Z")
}
})Dry Run
Let's trace the query for dates between 2023-01-01 and 2023-01-31.
Input Dates
Start date = 2023-01-01T00:00:00Z, End date = 2023-01-31T23:59:59Z
Filter Documents
Check each document's dateField to see if it is >= start date and <= end date
Return Matches
Documents with dateField 2023-01-10 and 2023-01-20 are returned
| Document _id | dateField | Matches Range? |
|---|---|---|
| 1 | 2023-01-10T12:00:00Z | Yes |
| 2 | 2023-01-20T08:30:00Z | Yes |
| 3 | 2023-02-01T00:00:00Z | No |
Why This Works
Step 1: Use $gte and $lte
The $gte operator selects documents with dates greater than or equal to the start date, and $lte selects those less than or equal to the end date.
Step 2: Dates stored as ISODate
Dates in MongoDB are stored as ISODate objects, which allow accurate comparison using these operators.
Step 3: Combined condition filters range
Combining $gte and $lte in one query filters documents whose dateField falls within the inclusive range.
Alternative Approaches
db.collection.find({
$and: [
{ dateField: { $gte: ISODate("2023-01-01") } },
{ dateField: { $lte: ISODate("2023-01-31") } }
]
})db.collection.find({
$expr: {
$and: [
{ $gte: ["$dateField", ISODate("2023-01-01")] },
{ $lte: ["$dateField", ISODate("2023-01-31")] }
]
}
})Complexity: O(n) time, O(k) space
Time Complexity
The query scans documents and compares each dateField, so time grows linearly with the number of documents.
Space Complexity
Space depends on the number of matching documents returned, stored in memory as k.
Which Approach is Fastest?
Using direct $gte and $lte operators is fastest and simplest; $expr adds overhead and is slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $gte and $lte | O(n) | O(k) | Simple and efficient date range queries |
| $and with $gte and $lte | O(n) | O(k) | When combining multiple conditions explicitly |
| $expr with $and | O(n) | O(k) | Complex expressions but slower performance |