一.mongodb通过设置TTL索引,自动删除过期的文档:
例如,下面的操作创建的索引 log_events
集合的createdAt
字段和指定 expireAfterSeconds
的值3600
来设置的到期时间是1小时通过指定的时间之后createdAt
。
1.建立TTL索引
db .log_events .createIndex ( { “ createdAt ” : 1 }, { expireAfterSeconds : 3600 } )
2.插入数据
db.log_events.insert ({
“createdAt” : new Date (), //数据库根据此字段,判断自动删除文档
“logEvent” : 2 ,
“logMessage” : “Success!”
})
二 golang 通过mgo实现
package models import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "testing" "time" ) type Mail struct { IsNew bool `json:"is_new"` //是不是新增的邮件 IsRead bool `json:"is_read"` //是否已读 IsRemove bool `json:"is_remove"` //邮件是否删除 Id string `json:"id"` //邮件id OpenId string `json:"-"` //id RoleName string `json:"rolename"` // Goods []*Item `json:"goods"` //发放的物品 Title string `json:"title"` //邮件标题 Content string `json:"content"` //邮件内容 SendTime int64 `json:"sendtime"` //邮件发送时间 IndexTime time.Time `json:"-"` //邮件删除时间 } func TestDBMailSet(t *testing.T) { session, err := mgo.Dial("127.0.0.1:27017") defer session.Close() if err != nil { fmt.Println(err) } db := session.DB("mail") c := db.C(fmt.Sprintf("游客%d", 10)) index := mgo.Index{ Key: []string{"indextime"}, // 索引字段 /* Unique: true, DropDups: true, Sparse: true,*/ Background: true, // 后台创建索引 ExpireAfter: 120*time.Second, //120s后删除 } err = c.EnsureIndex(index) if err != nil { fmt.Println("dfasf", err.Error()) } mail :=&Mail{Title:"你好",Content:"怎么样",IndexTime:time.Now().Local()} info, err := c.Upsert(bson.M{"mailid": mail.Id}, bson.M{"$set": mail}) // fmt.Printf("dderf%#s,%#v",mail.Id,mail) if err != nil { fmt.Print("DBMailSet 保存数据异常:%s", err.Error(),info) } }