MongoDB Query to Find Records Between Dates
db.collection.find({ dateField: { $gte: ISODate("start_date"), $lte: ISODate("end_date") } }) to find records between two dates in MongoDB.Examples
How to Think About It
$gte for 'greater than or equal' and $lte for 'less than or equal' operators to specify this range.Algorithm
Code
db.records.find({
date: {
$gte: ISODate("2023-01-01T00:00:00Z"),
$lte: ISODate("2023-01-31T23:59:59Z")
}
})Dry Run
Let's trace finding records between 2023-01-01 and 2023-01-31 through the query.
Set date range
Start date = 2023-01-01T00:00:00Z, End date = 2023-01-31T23:59:59Z
Filter records
Check each record's date if it is >= start date and <= end date
Return matching records
Records with dates 2023-01-10 and 2023-01-20 match and are returned
| Record _id | Record Date | Matches Range? |
|---|---|---|
| 1 | 2023-01-10T00:00:00Z | Yes |
| 2 | 2023-01-20T00:00:00Z | Yes |
| 3 | 2023-02-01T00:00:00Z | No |
Why This Works
Step 1: Use $gte operator
The $gte operator ensures the date is on or after the start date.
Step 2: Use $lte operator
The $lte operator ensures the date is on or before the end date.
Step 3: Combine conditions
Both operators together filter the date field to the desired range inclusively.
Alternative Approaches
db.records.find({ $and: [ { date: { $gte: ISODate("2023-01-01") } }, { date: { $lte: ISODate("2023-01-31") } } ] })db.records.find({ $expr: { $and: [ { $gte: ["$date", ISODate("2023-01-01")] }, { $lte: ["$date", ISODate("2023-01-31")] } ] } })Complexity: O(n) time, O(k) space
Time Complexity
The query scans documents in the collection; if an index on the date field exists, it speeds up to O(log n). Without an index, it is O(n) scanning all documents.
Space Complexity
The space depends on the number of matching documents k returned; no extra space is used for filtering.
Which Approach is Fastest?
Using direct $gte and $lte operators is fastest and simplest. Using $and or $expr adds overhead and complexity without performance benefits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $gte and $lte operators | O(log n) with index | O(k) | Simple and efficient date range queries |
| $and operator | O(log n) with index | O(k) | Explicit condition combination, less concise |
| $expr with $and | O(log n) with index | O(k) | Complex expressions, less readable for simple queries |