MongoDB设置过期删除文件(一条命令搞定)

一共有两种方式,第一种是直接指定在某个时间删除,第二种是指定在某个创建时间多久之后删除。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值