我正在嘗試使用mongo-go-driver做一些簡單的事情。我在集合中插入了一些資料,我希望它們在幾秒鐘后被自動洗掉。
我已閱讀以下檔案:https : //docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds
然后我在 GO 中寫了一些東西,但它似乎沒有按我預期的那樣作業。也許有些東西我沒有得到,或者我做錯了。
package main
import (
"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)
}
// I expect some datas not to be there (less than 5)
fmt.Println(datas)
}
type NFT struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
CreatedAt time.Time `bson:"createdAt,omitempty"`
Timestamp time.Time `bson:"timestamp,omitempty"`
Name string `bson:"name,omitempty"`
}
uj5u.com熱心網友回復:
你的例子沒有任何問題,它有效。
請注意,expireAfterSeconds您指定的是createdAt檔案過期后的持續時間,該時刻是檔案可能被洗掉的最早時間,但不能保證洗掉會“立即”發生,恰好在那個時間。
參考MongoDB 檔案:TTL 索引:洗掉操作的時間:
TTL 索引不保證過期資料會在過期后立即洗掉。檔案過期時間和 MongoDB 從資料庫中洗掉檔案的時間之間可能存在延遲。
洗掉過期檔案的后臺任務每 60 秒運行一次。因此,在檔案到期和后臺任務運行之間的時間段內,檔案可能會保留在集合中。
由于洗掉操作的持續時間取決于您的mongod實體的作業負載,因此在后臺任務運行之間的 60 秒時間段之后,過期資料可能會存在一段時間。
如您所見,如果檔案過期,在最壞的情況下,后臺任務可能需要 60 秒才能啟動并開始洗掉過期檔案,如果有很多(或資料庫負載過重),則可能需要一些時間是時候洗掉所有過期的檔案了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329209.html
