Spring Boot MongoDB Indexed with expireAfterSeconds to Auto delete Document does not work Spring Boot MongoDB Indexed with expireAfterSeconds to Auto delete Document does not work mongodb mongodb

Spring Boot MongoDB Indexed with expireAfterSeconds to Auto delete Document does not work


Here is explanation: "The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task."


First check that the index is properly created. Using mongo-shell, you can do db.collection.getIndexes() which should return the given collection's indexes along the TTL index e.g.

[    {        "v" : 2,        "key" : {            "_id" : 1        },        "name" : "_id_",        "ns" : "sample.collectionsName"    },    {        "v" : 2,        "key" : {            "dateField" : 1        },        "name" : "dateField",        "ns" : "sample.collectionname",        "expireAfterSeconds" : NumberLong(5)    }]

If this doesn't work, you'll need to enable index creation with

      auto-index-creation: true

After all this is set, you should see your documents are getting deleted indeed, however take the mongod-ttl job into consideration. This job runs every 60 seconds, which means that your documents with the TTL index could initially miss the first cleanup run and would require +60seconds to be deleted.

This is perfectly described in the docs that JJussi pinned as well.

TTL Indexes - MongoDB