Date and timestamp types in MongoDB - Time & Space Complexity
When working with dates and timestamps in MongoDB, it's important to understand how operations on these types grow as data increases.
We want to know how the time to process date or timestamp data changes when we have more records.
Analyze the time complexity of the following MongoDB query.
db.events.find({
eventDate: { $gte: new Date('2023-01-01'), $lt: new Date('2024-01-01') }
})
This query finds all events with a date in the year 2023.
Look for repeated work done by the database to answer the query.
- Primary operation: Scanning documents to check if their eventDate falls in the given range.
- How many times: Once for each document in the collection if no index is used.
As the number of documents grows, the database checks more dates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 date checks |
| 100 | 100 date checks |
| 1000 | 1000 date checks |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to find matching dates grows in a straight line as the data grows.
[X] Wrong: "Checking dates is always fast because dates are simple."
[OK] Correct: Even simple date checks take time for each document, so without an index, more data means more work.
Understanding how queries on dates scale helps you explain how databases handle time-based data efficiently.
What if we added an index on the eventDate field? How would the time complexity change?