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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?