Home > OS >  MongoDB node.js : Delete a document automatically after 10 seconds
MongoDB node.js : Delete a document automatically after 10 seconds

Time:12-20

I want to delete a document automatically after 10 seconds of creating It , for doing this I use mongodb TTL ,But the timer doesn't works properly and deletes the document after 40 seconds or 50 seconds or 20, So where is my mistake ?

  await db.collection("admin_msg").insertOne({ createdAt: new Date() });
  await db.collection("admin_msg").createIndex({ createdAt: 1}, { expireAfterSeconds: 10 });

CodePudding user response:

expireAfterSeconds doesn't guarantee immediate deletion of the document. The deletions are done by a background job which runs every minute. This job is low-priority and can be postponed by MongoDB when the current load is high. So when it's important for your use-case that the expire times are respected accurately to the second, then you should add the expiration time to the find-query to make sure you don't get any documents which are already supposed to be deleted.

This feature is documented here: http://docs.mongodb.org/manual/tutorial/expire-data/

I would not recommend to create an own job to automatically delete documents and runs at shorter intervals, as that might not only cause quite a lot of load, it might also not actually fix the problem, because those deletions might also get delayed when the oplog gets too long. Checking the expiration on retrieval is a far more reliable option.

CodePudding user response:

As the mongo docs states:

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.

So if the document needs to be deleted exactly after 10 seconds you're going to have to write your own service, job or other programmable method to delete a document after a specific amount of time.

  • Related