我正在尝试使用mongo-go-driver做一些简单的事情。我在集合中插入了一些数据,我希望它们在几秒钟后被自动删除。我已阅读以下文档:https ://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds然后我在 GO 中写了一些东西,但它似乎没有像我预期的那样工作。也许有些东西我没有得到,或者我做错了。package mainimport ( "bytes" "context" "fmt" "log" "text/tabwriter" "time" "github.com/Pallinder/go-randomdata" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options")func main() { ctx := context.TODO() client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { log.Fatal(err) } err = client.Connect(ctx) if err != nil { log.Fatal(err) } db := client.Database("LADB") col := db.Collection("LACOLL") // add index to col // the goal is to set a TTL for datas to only 1 secondes (test purpose) model := mongo.IndexModel{ Keys: bson.M{"createdAt": 1}, Options: options.Index().SetExpireAfterSeconds(1), } ind, err := col.Indexes().CreateOne(ctx, model) if err != nil { log.Fatal(err) } fmt.Println(ind) // insert some datas each seconds for i := 0; i < 5; i++ { name := randomdata.SillyName() res, err := col.InsertOne(ctx, NFT{Timestamp: time.Now(), CreatedAt: time.Now(), Name: name}) if err != nil { log.Fatal(err) } fmt.Println("Inserted", name, "with id", res.InsertedID) time.Sleep(1 * time.Second) } // display all cursor, err := col.Find(ctx, bson.M{}, nil) if err != nil { log.Fatal(err) } var datas []NFT if err = cursor.All(ctx, &datas); err != nil { log.Fatal(err) }
1 回答

aluckdog
TA贡献1847条经验 获得超7个赞
您的示例没有任何问题,它有效。
请注意,expireAfterSeconds
您指定的时间createdAt
是文档过期后的持续时间,而该时刻是文档可能被删除的最早时间,但不能保证删除会“立即”发生,即在那个时间。
TTL 索引不保证过期数据会在过期后立即被删除。文档过期和 MongoDB 从数据库中删除文档的时间之间可能存在延迟。
删除过期文档的后台任务每 60 秒运行一次。因此,在文档到期和后台任务运行之间的时间段内,文档可能会保留在集合中。
由于删除操作的持续时间取决于您的mongod实例的工作负载,因此在后台任务运行之间的 60 秒时间间隔之后,过期数据可能会存在一段时间。
如您所见,如果一个文档过期,最坏的情况下,后台任务可能需要 60 秒才能启动并开始删除过期文档,如果有很多(或数据库负载过重),则可能需要一些是时候删除所有过期的文件了。
- 1 回答
- 0 关注
- 331 浏览
添加回答
举报
0/150
提交
取消