I want to save data into MongoDB using pymongo, and it need to expire automatically after a month (maybe less) if noone removes it before (another script will perform a read + delete).
At the moment, I'm testing the TTL with expireAfterSeconds
, and it doesn't work the way I'd like. Here's my example :
client = MongoClient()
db = client.save_db
model = db.save_co
model.create_index("inserted", expireAfterSeconds = 120)
inserted_id = model.insert_one({"order_number":123456789, "inserted":datetime.datetime.utcnow()}).inserted_id
i = 1
while model.find_one(inserted_id) is not None:
time.sleep(1)
i += 1
print(i)
exit()
I think the printed value should be 120
, but it's actually 154
, or 160
, and sometimes 123
.
I don't get what I'm doing wrong, any help ? Thanks
From the docs: "The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database." See it here: https://docs.mongodb.com/v4.0/core/index-ttl/#timing-of-the-delete-operation