Shaghayegh Tavakoli
Shaghayegh Tavakoli

Reputation: 530

MongoDB - Updating TTL Index value

I'm trying to update the value of the expiry date in a document. Here's the Node.js code I use to set the index everytime I want to update the document:

database.collection(collectionName).createIndex({ "expires_on": 1 }, { expireAfterSeconds: 0 })
database.collection(collectionName).updateOne(query, update, { upsert: true }, (error, result) => {...})

The thing is that I set the expires_on date to the date of tomorrow and the value is set correctly in database but it expires within a few seconds. Is there a problem with the way I'm updating this field? I don't know how I can update this document in a way that it would expire on the last expires_on date it has been updated for.

I have noticed that you can't update the indexes in MongoDB but am I updating the index here? Isn't it different when I try to change the value, not the index itself?

Upvotes: 1

Views: 1447

Answers (2)

Shaghayegh Tavakoli
Shaghayegh Tavakoli

Reputation: 530

The fact I was creating an index every time a new data was inserted was not logical. I set the index in my database once and only updated the document each time:

database.collection(collectionName).updateOne(query, update, { upsert: true }, (error, result) => {...})

However, the problem turned out to be the value I set for the expires_on in my code. Due to the asynchronicity of Node.js, the value wasn't calculated correctly.

Upvotes: 0

JJussi
JJussi

Reputation: 1580

You have understood ttl index bit strange way... In your code example you set every document what have timestamp column "expires_on" to expire right now (expireAfterSeconds: 0).

Expiring process is running background and if you set expireAfterSeconds to 0, it will find out all documents which "expires_on" value is less or equal to now().

So, your update of field "expires_on" must happen at moment where "now() -lt expires_on".

Better say f.ex. "expireAfterSeconds: 3600" and then update expires_on to value "tomorrow minus that 3600 seconds"...

Upvotes: 1

Related Questions