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 ?
Apart of the @Neil answer above, the documentation states, that
You cannot use
createIndex()
to change the value ofexpireAfterSeconds
of an existing index. Instead use thecollMod
database command in conjunction with theindex
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With