Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 832
Running Turtle Avatar asked Dec 05 '22 04:12

Running Turtle


2 Answers

Apart of the @Neil answer above, the documentation states, that

You cannot use createIndex() to change the value of expireAfterSeconds of an existing index. Instead use the collMod database command in conjunction with the index collection flag. Otherwise, to change the value of the option of an existing index, you must drop the index first and recreate.

So

db.runCommand({
  "collMod": <collection>,
  "index": {
    keyPattern: <index_spec>,
    expireAfterSeconds: <seconds>
  }
})

should work fine too.

like image 118
Benjamin Avatar answered Dec 09 '22 14:12

Benjamin


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.

like image 29
Neil Lunn Avatar answered Dec 09 '22 13:12

Neil Lunn