一共有两种方式,第一种是直接指定在某个时间删除,第二种是指定在某个创建时间多久之后删除。
1.指定在某个时间删除文件
给collection创建一个expire索引
db.logAutoDel.createIndex({"expireAt":1}, {"expireAfterSeconds":0})
### expireAt字段可自定义名称
插入一条数据试试,插入数据时带上expireAt字段
db.logAutoDel.insert({"createAt":new Date(), "msg":"hello world~~~"})
2.指定在创建时间后的某个期限删除
db.logAutoDel.createIndex({"createAt":1}, {"expireAfterSeconds":0})
## createAt字段可自定义
插入一条数据试试
db.logAutoDel.insert({"createAt":new Date(), "msg":"hello world~~~"})
测试可能无效的原因
MongoDB的TTL线程每60s才会执行一次
如果需要精确到1分钟之内可以自行调整TTL的执行周期
pymongo
在python中插入时间可以用datetime.datetime.utcnow() 来获取对应格式的时间
如果要设定当前时间的1h后可以用datetime.datetime.utcnow()+datetime.timedelta(seconds=3600)
几个须掌握的相关操作命令
1.查看当前所有索引
db.logAutoDel.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "bm_hub.logAutoDel"
},
{
"v" : 2,
"key" : {
"createAt" : 1,
"expireAfterSeconds" : 10
},
"name" : "createAt_1_expireAfterSeconds_10",
"ns" : "bm_hub.logAutoDel"
}
]
2.删除某个索引
# 找到对应的name即可
db.logAutoDel.dropIndex("createAt_1_expireAfterSeconds_10")
参考地址
https://stackoverflow.com/questions/27976726/mongodb-ttl-not-working