how do I create a TTL (time to live) index with golang and mongodb? This is how I'm trying to do it currently:
sessionTTL := mgo.Index{
Key: []string{"created"},
Unique: false,
DropDups: false,
Background: true,
ExpireAfter: session_expire} // session_expire is a time.Duration
if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
panic(err)
}
But if I look it up using:
db.session.getIndexes()
session_expire is set to 5*time.Second. The field "created" in the document is set to current date using time.Now(), so I expected the documents the be deleted after 5 seconds.
So the issue was that I had to drop the collection. The index existed already so it was not recreated with the expiration constraint.
I was trying to use the answer to this question, and ran into a problem. Consider the following small change:
sessionTTL := mgo.Index{
Key: []string{"created"},
Unique: false,
DropDups: false,
Background: true,
ExpireAfter: 60 * 60} // one hour
if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
panic(err)
}
The problem with this is that the code silently fails if ExpireAfter
is not a proper time.Duration
.
I had to change to: ExpireAfter: time.Duration(60 * 60) * time.Second,