TTL indexes for auto-expiry in MongoDB - Time & Space Complexity
When using TTL indexes in MongoDB, it's important to understand how the system handles automatic deletion of expired documents.
We want to know how the time to remove expired data grows as the collection gets bigger.
Analyze the time complexity of this TTL index setup and expiry process.
// Create TTL index on 'createdAt' field with 3600 seconds expiry
db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
// MongoDB background thread periodically removes expired documents
// No explicit query needed; system handles expiry automatically
This code creates a TTL index that automatically deletes documents older than one hour.
MongoDB runs a background thread that periodically scans for expired documents.
- Primary operation: Scanning documents with the TTL index to find expired ones.
- How many times: This scan repeats regularly, roughly every 60 seconds.
The background thread uses the TTL index to quickly find expired documents without scanning the whole collection.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few index lookups, very fast |
| 100 | More index lookups, still quick |
| 1000 | More lookups but still efficient due to index |
Pattern observation: The time to find expired documents grows slowly because the TTL index helps avoid scanning all documents.
Time Complexity: O(log n + m)
This means the time to find expired documents grows slowly as the collection grows, thanks to the index, plus the time to delete the expired documents (m).
[X] Wrong: "TTL expiry scans every document in the collection each time it runs."
[OK] Correct: MongoDB uses the TTL index to quickly locate expired documents, so it does not scan all documents every time.
Understanding how TTL indexes work and their time complexity shows you know how databases handle automatic cleanup efficiently.
"What if the TTL index was on a non-indexed field? How would the time complexity change?"
Practice
Solution
Step 1: Understand TTL index function
A TTL index is designed to remove documents automatically after a certain time period.Step 2: Compare options with TTL purpose
Only Automatically delete documents after a specified time describes automatic deletion after time, which matches TTL index behavior.Final Answer:
Automatically delete documents after a specified time -> Option AQuick Check:
TTL index = auto-delete documents [OK]
- Thinking TTL encrypts data
- Confusing TTL with backup or sorting
- Assuming TTL speeds up queries
createdAt that expires documents after 3600 seconds?Solution
Step 1: Recall correct TTL index syntax
The correct syntax uses createIndex with the option expireAfterSeconds set to the expiry time in seconds.Step 2: Match options with correct syntax
Only db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) uses createIndex and expireAfterSeconds correctly.Final Answer:
db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) -> Option AQuick Check:
expireAfterSeconds option = correct TTL syntax [OK]
- Using wrong option names like ttl or expireAfter
- Using non-existent createTTLIndex method
- Forgetting to specify expireAfterSeconds
timestamp field and a TTL index created as db.logs.createIndex({ timestamp: 1 }, { expireAfterSeconds: 120 }), what happens to a document inserted with { timestamp: new Date() } after 3 minutes?Solution
Step 1: Understand TTL expiry timing
The TTL index deletes documents after expireAfterSeconds from the timestamp field value.Step 2: Calculate expiry for 3 minutes
3 minutes = 180 seconds, which is more than 120 seconds, so the document will be deleted.Final Answer:
The document is automatically deleted -> Option BQuick Check:
TTL expiry after 120s means deletion after 3 minutes [OK]
- Thinking document stays forever
- Assuming TTL archives instead of deletes
- Believing TTL causes insertion errors
expireAfterSeconds: 0 on a field expireAt, but documents are not being deleted. What is the likely cause?Solution
Step 1: Check TTL index requirements
TTL indexes require the indexed field to be a date type to calculate expiry.Step 2: Analyze why documents not deleted
If expireAt is not a date, TTL cannot determine expiry time, so documents stay.Final Answer:
The expireAt field is not a date type -> Option DQuick Check:
TTL needs date field type to delete documents [OK]
- Thinking expireAfterSeconds cannot be zero
- Believing TTL only works on _id
- Assuming MongoDB restart is needed
expireAt field. Which TTL index configuration achieves this?Solution
Step 1: Understand TTL with exact expiry date
Setting expireAfterSeconds to 0 means documents expire exactly at the date/time in the field.Step 2: Compare options for exact expiry
Only Create TTL index onexpireAtwithexpireAfterSeconds: 0uses expireAfterSeconds: 0 on expireAt field to expire exactly at that time.Final Answer:
Create TTL index on expireAt with expireAfterSeconds: 0 -> Option CQuick Check:
expireAfterSeconds: 0 = expire exactly at date field [OK]
- Using non-zero expireAfterSeconds for exact expiry
- Confusing createdAt with expireAt field
- Relying on manual background jobs unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
