I am looking into deleting a document at a specific time.
const TestSchema = new Schema({
expire_at: {
type: Date,
},
}, {
timestamps: true,
});
TestSche
To delete MongoDB document in specific time you can use TTL (time to live). TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time.
So you need to create a TTL index like: (mongo shell command)
db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
or you can use mongoose to create this index
TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
then mongodb check after every 60 second and if expire_at
date time is less than the current date time then this record will remove after 5 second.
The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.
The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.
TTL Indexes
NB: Use createIndex
instead of index
As Amit noted, TTL Indexes are not guaranteed to delete data at the time of expiration; the background task to expire data will run every 60 seconds.
The background tasks can also be affected by performance contention and workload, which can cause data to exist far beyond this window:
The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.
Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.
Source
Deletion process runs after 60 seconds. So document can be there for 59 seconds after the deletion time has been passed.
This will delete the document in two hours:
const TestSchema = new Schema({
expire_at: {type: Date, default: Date.now, expires: 7200}
})
//expired in 2 hours