Remove old data from MongoDB

Today we will be looking at how to remove old records in MongoDB based on X days. Before we do anything, we need to generate a list of documents for the database:

For this example, we have 10 documents. We need to remove documents that are older than X days :

and for sure we must write a Cron job to do this.

Start Cron at 12:00 AM every day. You can use npm package to do this.

example of cron.js:

Let’s automate it without programming Cron.

That’s all we need to do. Simple, right? :)

For more information about MongoDB TTL indexes, please visit Expire Data from Collections by Setting TTL.

If you have any questions or feedback about this article, feel free to leave a comment.
Thanks for reading and Let’s join our team.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store