简体   繁体   English

每 24 小时从 MongoDB 中删除项目

[英]Delete items from MongoDB every 24 hours

I have a MongoDB in the form:我有一个 MongoDB 的形式:

{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?我有一个 Python 代码每 10 分钟查询一次数据库,我想删除所有超过 24 小时的项目,该怎么做?

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.我不会通过 python 手动删除数据,而是直接在您的数据库中进行设置。

A quick search results in MongoDB naming this feature "Time to Live" or TTL MongoDB 中的快速搜索结果将此功能命名为“生存时间”或 TTL

Although I would recommend Teejay Bruno's answer this would be a valid solution:虽然我会推荐 Teejay Bruno 的回答,但这将是一个有效的解决方案:

import time


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM