0
0
MongoDBquery~30 mins

TTL indexes for auto-expiry in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the sessions collection and insert a session document
Create a collection called sessions and insert one document with a createdAt field set to the current date and time using new Date().
MongoDB
Need a hint?

Use db.sessions.insertOne({ createdAt: new Date() }) to insert the document.

2
Define the TTL index expiration time
Create a variable called expireAfterSeconds and set it to 3600 to represent the expiration time in seconds.
MongoDB
Need a hint?

Use const expireAfterSeconds = 3600 to set the expiration time.

3
Create the TTL index on createdAt
Use db.sessions.createIndex to create a TTL index on the createdAt field with the option { expireAfterSeconds: expireAfterSeconds }.
MongoDB
Need a hint?

Use db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: expireAfterSeconds }) to create the TTL index.

4
Verify the TTL index creation
Use db.sessions.getIndexes() to list all indexes on the sessions collection and confirm the TTL index exists.
MongoDB
Need a hint?

Use db.sessions.getIndexes() to see all indexes on the collection.