是否有正确的方法使用official mongo driver按键配置数据自删除?我在Mongo-driver模块中找到的唯一方法是ExpireAfterSeconds,但我不确定如何正确使用它。这是现在准备就绪的repository。
您需要在字段上创建一个ttl索引,该索引需要在n秒后删除。
在下面的代码片段中,创建了一个expirationTime字段,可以在其上设置ttl。从记录中设置的expirationTime开始60秒后,记录将被删除。
以下是创建TTL索引的代码:
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")
}