Creating TTL index in MongoDB with Go mongo-go-driver

Md. Faysal Mahmud Abid
2 min readJan 19, 2021

Here, I don’t want to describe much about TTL index. I think the MongoDB documentation is enough to understand the concept and when this can be useful. So my main focus will be on implementation.

From the documentation:

TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time. Data expiration is useful for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.

Here we will see an example of a document named “session” where we will be creating a TTL index.

I am using mongo-go-driver the official Go library supported by MongoDB.

Run this command to install the pkg.

go get go.mongodb.org/mongo-driver/mongo

My model for the sessioncollection:

The function responsible for the endpoint and containing TTL implementation :

So, whenever the function will be executed a Document will be created in the session collection in your MongoDB Database. And after a certain time as you want, the Document will be removed automatically from the database.

--

--