Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
MongoDB node.js : Delete a document automatically after 10 seconds

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 });

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!