mongo 设置自动过期时间

Time To Live(TTL) 集合

MongoDB 2.2 引入一个新特性–TTL 集合,TTL集合支持失效时间设置,或者在某个特定时间,
集合自动清除超时文档,者用来保存一个诸如session会话信息的时候非常有用。

如果想使用TTL集合,用用到 expireAfterSeconds 选项

Expire Documents after a Specified Number of Seconds

首先创建索引,设置过期时间

1
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

然后存储数据入库

1
2
3
4
5
db.log_events.insert( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )

golang 使用mgo实现:

1
2
3
4
5
6
7
8
9
10
11
12
func CreateIndex() (err error) {
db := datasource.NewSessionStore()
defer db.Close()
col := db.C(log_events)
// Index
index := mgo.Index{
Key: []string{"createdAt"},
ExpireAfter: time.Second * 3600,
}
err = col.EnsureIndex(index)
return
}

Expire Documents at a Specific Clock Time

与上面的设置类似
首先建立索引,设置 expireAfterSeconds 为 0

1
db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )

然后存储数据

1
2
3
4
5
db.log_events.insert( {
"expireAt": new Date('July 22, 2013 14:00:00'),
"logEvent": 2,
"logMessage": "Success!"
} )

expireAt 的值为特定的时间值,等时间到达expireAt的值时,这个文档就失效了。
mgo里面好像没办法创建这种索引了