GAP2002
GAP2002

Reputation: 979

Delete items from MongoDB every 24 hours

I have a MongoDB in the form:

{Key : "XXXX-YYYY-ZZZZ-1234", timestamp : 1613776160493

I have a Python code to query the database every 10 minutes and I want to delete all items older than 24 hours, how would this be done?

Upvotes: 0

Views: 791

Answers (2)

GAP2002
GAP2002

Reputation: 979

Although I would recommend Teejay Bruno's answer this would be a valid solution:

import time

dayago = time.time() * 1000 - 86400000
col.delete_many({"timestamp": {"$lt": dayago}})

Upvotes: 1

Teejay Bruno
Teejay Bruno

Reputation: 2159

Most databases include this feature already in the form of a retention policy. Rather than manually delete data through python, I would just set this up directly in your database.

A quick search results in MongoDB naming this feature "Time to Live" or TTL

Upvotes: 2

Related Questions