0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Records Between Dates

Use db.collection.find({ dateField: { $gte: ISODate("start_date"), $lte: ISODate("end_date") } }) to find records between two dates in MongoDB.
📋

Examples

InputFind records with date between 2023-01-01 and 2023-01-31
Output[{ "_id": 1, "date": ISODate("2023-01-10T00:00:00Z"), "name": "Record A" }, { "_id": 2, "date": ISODate("2023-01-20T00:00:00Z"), "name": "Record B" }]
InputFind records with date between 2023-06-01 and 2023-06-01 (single day)
Output[{ "_id": 3, "date": ISODate("2023-06-01T00:00:00Z"), "name": "Record C" }]
InputFind records with date between 2022-12-01 and 2022-12-31 (no records)
Output[]
🧠

How to Think About It

To find records between two dates, think of filtering documents where the date field is greater than or equal to the start date and less than or equal to the end date. MongoDB uses $gte for 'greater than or equal' and $lte for 'less than or equal' operators to specify this range.
📐

Algorithm

1
Get the start date and end date as input.
2
Use the $gte operator to filter records with date greater than or equal to the start date.
3
Use the $lte operator to filter records with date less than or equal to the end date.
4
Combine both conditions in a query on the date field.
5
Run the query to get all matching records.
💻

Code

mongodb
db.records.find({
  date: {
    $gte: ISODate("2023-01-01T00:00:00Z"),
    $lte: ISODate("2023-01-31T23:59:59Z")
  }
})
Output
[ { "_id": 1, "date": ISODate("2023-01-10T00:00:00Z"), "name": "Record A" }, { "_id": 2, "date": ISODate("2023-01-20T00:00:00Z"), "name": "Record B" } ]
🔍

Dry Run

Let's trace finding records between 2023-01-01 and 2023-01-31 through the query.

1

Set date range

Start date = 2023-01-01T00:00:00Z, End date = 2023-01-31T23:59:59Z

2

Filter records

Check each record's date if it is >= start date and <= end date

3

Return matching records

Records with dates 2023-01-10 and 2023-01-20 match and are returned

Record _idRecord DateMatches Range?
12023-01-10T00:00:00ZYes
22023-01-20T00:00:00ZYes
32023-02-01T00:00:00ZNo
💡

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

Using $and operator
mongodb
db.records.find({ $and: [ { date: { $gte: ISODate("2023-01-01") } }, { date: { $lte: ISODate("2023-01-31") } } ] })
This is more verbose but explicitly shows the two conditions combined with $and.
Using $expr with $and
mongodb
db.records.find({ $expr: { $and: [ { $gte: ["$date", ISODate("2023-01-01")] }, { $lte: ["$date", ISODate("2023-01-31")] } ] } })
Uses aggregation expression in find; useful for complex queries but less readable for simple date ranges.

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.

ApproachTimeSpaceBest For
$gte and $lte operatorsO(log n) with indexO(k)Simple and efficient date range queries
$and operatorO(log n) with indexO(k)Explicit condition combination, less concise
$expr with $andO(log n) with indexO(k)Complex expressions, less readable for simple queries
💡
Always use ISODate format for date comparisons in MongoDB to avoid timezone issues.
⚠️
Forgetting to use ISODate() and comparing dates as strings, which leads to incorrect results.