dpb42021 2019-03-11 13:19
浏览 116
已采纳

为收集的过期数据设置TTL

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")
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波