[GODRIVER-1218] How to create a TTL index on a collection Created: 05/Aug/19  Updated: 12/Aug/19  Resolved: 12/Aug/19

Status: Closed
Project: Go Driver
Component/s: Core API
Affects Version/s: 1.0.4
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Andrew Lee Assignee: Divjot Arora (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

macOS/Ubuntu



 Description   

How can I go about doing something like what is defined here: https://docs.mongodb.com/manual/tutorial/expire-data/ using Go MongoDB driver?

I presume I would have to do this at the collection level. It doesn't seem like I can use RunCommand on a collection object.

 

The specific command I am trying to run would be `db.log_events.createIndex(

{ "createdAt": 1 }

,

{ expireAfterSeconds: 3600 }

)`.



 Comments   
Comment by Andrew Lee [ 07/Aug/19 ]

Nevermind. I figured it out.

 

For anyone wondering, the code is as follows:

 

{{db := client.Database(DB_NAME) db := client.Database(DB_NAME)collection := client.Database(DB_NAME).Collection(_COLLECTION_NAME) opts := options.CreateIndexes() opts := options.CreateIndexes()}}
{{ {{ keys := bsonx.Doc{{Key: "createdAt", Value: bsonx.Int32(int32(1))}} index := mongo.IndexModel{} index.Keys = keys index.Options = options.Index().SetExpireAfterSeconds(60)}}}}
{{ {{ collection.Indexes().CreateOne(context.Background(), index, opts)}}}}
{{ {{ if err != nil

{ log.Fatal(err) }

}}}}

Generated at Thu Feb 08 08:35:56 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.