首页 文章

Mongodb TTL提前到期文件

提问于
浏览
5

我正在尝试将文档插入Mongo数据库,并在预定时间后自动使其自动过期 . 到目前为止,我的文档被插入但总是从0到60秒从数据库中删除,即使我将'expireAfterSeconds'设置得更长 . 我知道mongodb大约每60秒删除一次过期的文档,所以似乎'expredAfterSeconds'变量不起作用 .

我按照这里的文档:Mongodb TTL Docs

这是我的测试代码,它应该在3分钟后过期(删除)文档(但它会在一分钟内完成):

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

有没有人有任何想法是什么问题?

2 回答

  • 3

    对于Pymongo 3,这是更新的语法 .

    mongo_collection.create_index("date", expireAfterSeconds=3*60)
    
  • 14

    您的问题来自于在当地时区使用天真的时间戳 . FAQ of pymongo有一个条目,其中包含不使用 datetime.datetime.now() 的警告 . 使用 utcnowttl -set按预期工作:

    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
    

相关问题