MongoDB expireAt doesn't fire immediately

Viewed 18

I set a document to expire at exactly 2022-09-10T01:42:00.000+00:00

But the document doesn't get deleted immediately, several seconds passed by before it eventually gets deleted.

Is there a way to make expireAt fire immediately the time is reached? It shouldn't wait for an extra second at all?

This is the structure of my schema

const EventSchema = new mongoose.Schema(
    {
        _id: mongoose.Schema.Types.ObjectId,
        expireAt: { type: Date, expires: 0 }
    },
    { timestamps: true }
);

EventSchema.index({ "expireAt": 1 }, { expireAfterSeconds: 0 })

My use case is mongoose.

Thanks

1 Answers

The MongoDB TTL index feature will remove the document some time after it has expired.

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time that 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. MongoDB starts deleting documents 0 to 60 seconds after the index completes.

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.

Similar expire functionality could be implemented in your application if more accurate timing is required.

Related