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 ?
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 ?
Share Improve this question edited Jun 30, 2017 at 8:10 Neil Lunn 151k36 gold badges354 silver badges324 bronze badges asked Mar 9, 2015 at 10:35 Running TurtleRunning Turtle 12.8k20 gold badges57 silver badges81 bronze badges 1- docs.mongodb.com/v3.0/tutorial/modify-an-index – PPB Commented Dec 14, 2017 at 11:12
3 Answers
Reset to default 11Apart 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.
From: https://docs.mongodb.com/manual/tutorial/expire-data/
You can modify the expireAfterSeconds of an existing TTL index using the collMod command.
See Rob's answer here: https://stackoverflow.com/a/30174928/6088194
Rob's method worked for me. I updated the TTL index from weeks to 2 minutes and the previously loaded in documents started to be removed from the database once they exceeded the new expiration period.
EDIT: note that if authentication is enabled for Mongo then the 'collMod' command requires dbAdmin or adAminAnyDatabase privileges