Mongodb TTL expires documents early

前端 未结 2 770
臣服心动
臣服心动 2021-02-09 13:15

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 fr

相关标签:
2条回答
  • 2021-02-09 13:53

    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
    
    0 讨论(0)
  • 2021-02-09 14:04

    For Pymongo 3 this is the updated Syntax.

    mongo_collection.create_index("date", expireAfterSeconds=3*60)
    
    0 讨论(0)
提交回复
热议问题