TTL Indexes in MongoDB are very useful for storing data like logs or user sessions. The document will remove itself after a certain amount of time which is specified by the index. This tutorial will be done in both JavaScript and TypeScript using Node.js with node-mongodb-native, which is the official MongoDB Node.js driver.
Connect to the MongoDB server and select the database:
JavaScript
constMongoClient = require('mongodb').MongoClient;
asyncfunctioninit() {
constClient = awaitMongoClient.connect('mongodb://127.0.0.1:27017'); // change it to the address your MongoDB is listening onconstDatabase = Client.db('MyDatabase'); // change it to the database name of your choice
}
Javascript
TypeScript
import { MongoClient } from'mongodb';
asyncfunctioninit() {
constClient = awaitMongoClient.connect('mongodb://127.0.0.1:27017'); // change it to the address your MongoDB is listening onconstDatabase = Client.db('MyDatabase'); // change it to the database name of your choice
}
TypeScript
Make sure the MongoDB daemon is up and running in the background while connecting.
Select a collection, it'll create itself if it does not exist:
JavaScript
...
asyncfunctioninit() {
...
constCollection = Database.collection('MyCollection'); // change it to the collection name of your choice
}
Javascript
TypeScript
...
interfaceCollection_MyCollection {
date: Date;
msg: string;
} // create a interface specifying the type of the documentasyncfunctioninit() {
...
constCollection = Database.collection<Collection_MyCollection>('MyCollection'); // change it to the collection name of your choice
}
TypeScript
We'll create a function called printDocuments to print out the documents in the collection, and insert two documents with the current date and day before to see if they expire correctly:
...
asyncfunctioninit() {
...
asyncfunctionprintDocuments() {
console.log(awaitCollection.find({}).toArray()); // print all documents in the collection
}
awaitCollection.insertOne({
date: newDate(), // todaymsg: 'this won\'t expire soon',
});
awaitCollection.insertOne({
date: newDate(Date.now() - 60 * 60 * 24 * 1000), // yesterdaymsg: 'this will expire soon',
});
printDocuments();
setTimeout(() => {
printDocuments();
}, 60 * 2 * 1000); // since MongoDB only performs deletion every 60 seconds, we'll check the documents after 2 minutes
}
init(); // execute the functionJavascript
[
{
_id: new ObjectId("6203411f91c0d03dffa77509"),
date: 2022-02-09T04:20:47.313Z,
msg: "this won't expire soon"
},
{
_id: new ObjectId("6203411f91c0d03dffa7750a"),
date: 2022-02-08T04:20:47.317Z,
msg: 'this will expire soon'
}
]
Output
Be aware that MongoDB runs the background task that removes expired documents every 60 seconds, so there will be a short period of delay before the expired documents get deleted.