TTL Indexes for Auto-Expiry in MongoDB
📖 Scenario: You are managing a MongoDB database for a web application that stores temporary user session data. To keep the database clean and efficient, you want to automatically remove session documents after a certain time.
🎯 Goal: Build a MongoDB collection with a TTL index that automatically deletes session documents 3600 seconds (1 hour) after their creation.
📋 What You'll Learn
Create a collection named
sessions with documents containing a createdAt field of type Date.Add a TTL index on the
createdAt field with an expiration time of 3600 seconds.Insert a sample session document with the current date and time in
createdAt.Verify the TTL index is created correctly.
💡 Why This Matters
🌍 Real World
TTL indexes help automatically clean up temporary data like sessions, logs, or cache entries in databases, keeping storage efficient.
💼 Career
Understanding TTL indexes is useful for database administrators and backend developers managing data lifecycle and storage optimization.
Progress0 / 4 steps