Mongodb TTL提前使文档过期 [英] Mongodb TTL expires documents early
问题描述
我正在尝试将文档插入到Mongo数据库中,并使其在预定时间后自动过期.到目前为止,即使我将'expireAfterSeconds'设置的时间更长,我的文档仍然可以插入,但总是在0-60秒内从数据库中删除.我知道mongodb大约每60秒就会删除过期的文档,因此'expredAfterSeconds'变量似乎无法正常工作.
I am trying insert a document into a Mongo database and have it automatically expire itself after a predetermine time. So far, my document get inserted but always get deleted from the database from 0 - 60 seconds even though I set the 'expireAfterSeconds' to much longer. I know mongodb deletes expired documents about every 60 seconds so it seems the 'expredAfterSeconds' variable is not working.
我在这里关注了文档: Mongodb TTL文档
I followed the documentation here: Mongodb TTL Docs
这是我的测试代码,应该在3分钟后过期(删除)文档(但它在一分钟内就会完成):
Here is my test code that should expire (delete) the document after 3 minutes (but it does it under a minute):
import pymongo
import datetime
mongo_con = pymongo.Connection('localhost', 27017)
mongo_db = mongo_con.Mongo_database
mongo_col = mongo_db.my_TTL_collection
timestamp = datetime.datetime.now()
mongo_col.ensure_index("date", expireAfterSeconds=3*60)
mongo_col.insert({'_id': 'login_session', "date": timestamp, "session": "test session"})
有人有什么想法吗?
推荐答案
您的问题来自在本地时区中使用朴素的时间戳. pymongo的常见问题解答有一个条目,其中包含一个警告,请不要使用datetime.datetime.now()
.
使用utcnow
,ttl
设置可以按预期工作:
Your problems come from using naive timestamps in your local timezone. The FAQ of pymongo has an entry which includes a warning not to use datetime.datetime.now()
.
Using utcnow
, the ttl
-setting works as expected:
import pymongo
import datetime
mongo_con = pymongo.Connection('localhost', 27017)
mongo_db = mongo_con.Mongo_database
mongo_col = mongo_db.my_TTL_collection
timestamp = datetime.datetime.now()
utc_timestamp = datetime.datetime.utcnow()
mongo_col.ensure_index("date", expireAfterSeconds=3*60)
mongo_col.insert({'_id': 'session', "date": timestamp, "session": "test session"})
mongo_col.insert({'_id': 'utc_session', "date": utc_timestamp, "session": "test session"})
# the utc_session will be deleted after around 3 minutes,
# the other depending on your timezone
这篇关于Mongodb TTL提前使文档过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!