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
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