Is it possible to set the TTL per message in MongoDB? I want to insert messages that can have different TTL's and I use MongoDB to check if I have to resend a message
Asked
Active
Viewed 88 times
1 Answers
1
Yes, it's possible, see Expire Data from Collections by Setting TTL.
First you have to create a TTL index where you set 0
for expireAfterSeconds
. And you have to set the expireAt
timestamp, calculated by adding the wished TTL to the current time.
E.g. create an index:
db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
And then if you want 3 seconds TTL for a document, insert it with a property:
"expireAt": time.Now().Add(3 * time.Second)
To have a document with 1 hour TTL:
"expireAt": time.Now().Add(time.Hour)

icza
- 389,944
- 63
- 907
- 827