Is there a correct way to configure data self-deletion by key using the official mongo driver? The only method that I found in the Mongo-driver module is ExpireAfterSeconds, but I'm not sure how to use it correctly. Here's the repository with what is ready at the moment.
1条回答 默认 最新
douao2000 2019-03-11 14:11关注You need to create an ttl index on the field which needs to be removed after n seconds.
In the below code snippet, have created an expirationTime field on which ttl can be set. After 60 seconds from the expirationTime set in the record, the record will be removed.
Following is the code to create a TTL index:
var ttl *int32 *ttl = 60 keys := bsonx.Doc{{Key: "expirationTime", Value: bsonx.Int32(int32(1))}} idx := mongo.IndexModel{Keys: keys, Options: &options.IndexOptions{ExpireAfterSeconds: ttl}} _, err := collection.Indexes().CreateOne(context.Background(), idx) if err != nil { fmt.Println("Error occurred while creating index", err) } else { fmt.Println("Index creation success") }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报