Mongodb TTL expires documents early

前端 未结 2 772
臣服心动
臣服心动 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
    

提交回复
热议问题