javascriptnode.jsmongodbmongodb-querymongojs

How to update the TTL on a collection?


Using NodeJS + MongoJS, I have connection to a mongo DB.

I set a TTL on a collection with:

myCollection.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 30})

Is it now possible to update the value for expireAfterSeconds ? If so, what's the policy for already existing items in the collection, ie : are their TTL updated automatically or are they left untouched ?


Solution

  • You cannot actually "update" an index definition. What you need to here is "delete" the index and then "re-create" it. So use .dropIndex() first

    myCollection.dropIndex({ "createdAt": 1 },function(err,result) { });
    

    Then recreate with a new interval:

    myCollection.ensureIndex(
       { "createdAt": 1 },
       { "expireAfterSeconds": 60 * 10 },
       function(err,result) { }
    );
    

    As for when it updates, the mongod service runs at an interval every 60 seconds an event you process a delete for any items where the effective date field ( i.e "createdAt" in this example ) is within the "expiry period" from the current time of the server.

    So that means it does not matter if you drop the index and re-create it, as the existing server process will just run the same expiry query on each collection that has such an index defined on that interval clock.