How to use TTL collections in MongoDB?
Last Updated :
15 Jul, 2024
TTL (Time-To-Live) collections in MongoDB is a special collection where it allows automatic deletion of documents after a specified duration. This technique is used in managing temporary data, such as
How TTL Works
- TTL Index: You create a TTL index on a date field in your collection. This index determines when documents should be deleted based on the time elapsed since the date field's value.
- ExpireAfterSeconds: This option specifies the number of seconds after which documents should be removed. MongoDB's background task checks for expired documents approximately every 60 seconds.
- Delayed Deletion: Deletion isn't immediate; It depends on the session expiry time that you specify in your createIndex query and there may be a slight delay depending on the timing of the background task.
Approach
Mongodb provides a straightforward approach in implementing TTL Collections onto its application. We have to create a collection in MongoDB to store the data along with the temporary informations such as the user session, cache and logs , where these data has to be erased and updated from time to time. This is the core prinicple involved in the TTL Collection methodology.
TTL Index Creation
- After creating the desired collection, the main step involves in indexing the field and specifying the time for that particular document to expire.
- Below is the syntax for creating the index and setting the session timeout by using the create Index method. The main purpose of this funtion is to specify the field and duration after which documents should be deleted.
db.collection.createIndex({ <field>: 1 }, { expireAfterSeconds: <seconds> })
Steps to Create an Application
Step 1: Ensure that MongoDB is installed and running on your system. Then install the monogDB onto your application by running the following command in the terminal.
npm install mongodb
Folder Structure:
Fig: Folder StructureUpdated dependencies:
"dependencies": {
"express": "^4.19.2",
"mongodb": "^6.8.0",
"mongoose": "^8.5.1",
}
Step 2: After the successfull installation , ensure that the dependencies of MongoDB is succesfully installed in you package.json file. Your package.json file should look like below, after installing MongoDB. If it is not found , then you can manually type in the required latest version of the MongoDB in the package.json file.
Step 3: Use the MongoDB installed onto your application , by requiring the mongoClient using the require command in your server program
// index.js
const { MongoClient } = require('mongodb');
const client = new MongoClient("MONGO_URL);
Step 4: Connect to your database where your collections resides. Then create new collection named "UserSessions" to store the temporary documents onto the specified collection.
// index.js
await client.connect();
const database = client.db('myDatabase');
const collection = database.collection('userSessions');
Step 5: Specify the parameters of the new document to be inserted. Here we store the current date at which the document is inserted , in the variable named 'createdAt'.
// index.js
const session =
{ userId: "50",
sessionData: "GoingToExpire Data",
createdAt: new Date()
};
Step 6: After creating the required document, use createIndex function to index the createdAt field. Also specify the expiry time ,for which the document should be erased from the collection.
// index.js
await collection.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 30 });
Example: This example shows the use of TTL collection.
Node
const { MongoClient } = require('mongodb');
async function run() {
const uri =
"mongodb+srv://username:[email protected]/?retryWrites=true&w=majority&appName=Cluster0";
const client = new MongoClient(uri, { useUnifiedTopology: true });
try {
await client.connect();
const database = client.db('myDatabase');
const collection = database.collection('GFG');
// Insert a document with a createdAt field
const session = {
userId: "50",
sessionData: "GoingToExpire Data",
createdAt: new Date()
};
await collection.insertOne(session);
console.log("Inserted document:", session);
// Check if there is an existing TTL
// index on createdAt field and drop it
const indexes = await collection.indexes();
const createdAtIndex = indexes.find(index => index.key && index.key.createdAt);
if (createdAtIndex) {
await collection.dropIndex(createdAtIndex.name);
console.log("Dropped existing index:", createdAtIndex.name);
}
// Create a TTL index on the createdAt
// field to expire after 30 minutes (1800 seconds)
await collection.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 1800 });
console.log("TTL index created, documents will expire after 30 minutes");
// Verify the index was created
const newIndexes = await collection.indexes();
console.log("Current indexes on the collection:", newIndexes);
} catch (err) {
console.error("Error:", err);
} finally {
await client.close();
}
}
run().catch(console.error);
Output:
Fig: Console output after inserting the documentNote: After running the script, documents in the userSessions collection will automatically expire and be deleted 30 minutes after their createdAt timestamp.
Use Cases of TTL Collections
- Session Management: Automatically remove user sessions after they expire.It depends on the time in seconds, that you specify in the query.
- Cache Expiration: Clear out-of-date cache entries to ensure fresh data. These ensure that our data is clean and does not contain any cache and prevents deletion of cache manually.
- Log Retention: Keep logs for a specific duration for compliance or analysis.
Considerations while using TTL Collections
- Performance Impact: TTL indexes can affect performance, especially with large datasets or high insertion rates.
- Limitations: TTL indexes can't be part of compound indexes or used with sharded collections' shard keys.
- Date Field Accuracy: Ensure the date field used is correctly set to avoid premature or delayed deletions.
Conclusion
TTL collections in MongoDB offer an efficient way to manage the lifecycle of temporary data by automatically deleting expired documents. This not only keeps your database clean but also optimizes performance by reducing storage needs. By setting up a TTL index on a date field, or any other desired temporary fields, you can manage data such as user sessions, cache entries, or logs.There is no restriction to set index on any other field other that the date field. Understanding the limitations and proper configuration of TTL collections ensures that they are a valuable tool to integrate in your application.
Similar Reads
How to Use MongoDB in Eclipse?
Eclipse is an IDE (integrated development environment) used in computer programming. Eclipse is an IDE in which we can use any type of programming language for which plugins are available. It contains a base workspace and an extensible plug-in system for customizing the environment. Eclipse is free
5 min read
How to Rename Collection in MongoDB?
Renaming collections in MongoDB is a straightforward operation that helps in maintaining and organizing databases efficiently. MongoDB provides the renameCollection command and the db.collection.renameCollection() method for changing collection names within the same database.In this article, We will
3 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
Single vs Multiple Collections in MongoDB
MongoDB is a NoSQL database that provides flexibility in storing and managing data in the form of documents. One of the critical design decisions when structuring a MongoDB database is whether to use a single collection or multiple collections for organizing documents. This decision significantly im
4 min read
How to Add a Column in MongoDB Collection?
In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections. In this
4 min read
How to Sort a Collection by Date in MongoDB?
In MongoDB, sorting collections by date is a common requirement for many applications. Sorting by date allows us to display data in reverse order, making it easier for users to understand and analyze. In this article, we will explore different approaches to sorting collections by date in MongoDB, us
3 min read
How to List All Collections in the MongoDB Shell?
Managing collections is a fundamental task in MongoDB database administration. Knowing how to list all collections in the MongoDB shell is essential for understanding your database structure and managing your data effectively. In this article, we'll explore how to list all collections in the MongoDB
3 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
1 min read
How to add Timestamp in Mongodb Collection using Node.js ?
Timestamp: With the help of timestamp document in the collection of the MongoDB can be differentiated on the basis of time. We can add Timestamp in Mongodb Collection in Node.js using the following approach: Installing Module: Install the mongoose module using the following command: npm install mong
1 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read