MongoDB设置字段过期时间TTL(Time To Live )索引以及修改过期时间

MongoDB可以通过设置字段TTL(Time To Live )索引来设置过期时间


1、如下所示,test是Collection,设置Date1的过期时间10秒,只要在插入的数据中包含Date1字段,插入数据后10秒之后会自动删除该条数据
//创建字段的TTL(Time To Live )索引
db.test.ensureIndex({'Date1':1},{expireAfterSeconds:10})
db.test.insertOne({'Date1':new Date(),'Name':'lisi','Age':20})

//修改具有TTL索引的字段期时间,包括集合名称,具有指定TTL的字段的名称以及修改以后的过期时间秒,下面是将Date1过期时间从10秒改成20

db.runCommand({collMod: "test",index: { keyPattern: { Date1: 1 },expireAfterSeconds: 20}})


2、如下所示,test是Collection,设置Date1的过期时间0秒,只要在插入的数据中包含Date1字段,并且设置Date1位指定时间的时候,那么插入数据后,只要到Date1设置的时间就会自动删除该条数据
//创建字段的TTL(Time To Live )索引,这方式设置默认过期时间位0 ,但是可以指定什么时候过期
//db.test.ensureIndex({'Date1':1},{expireAfterSeconds:0})
//db.test.insertOne({'Date1':new Date('August 2, 2020 14:00:00'),'Name':'lisi','Age':20})

查询数据,观看数据的变化
db.test.find({})

猜你喜欢

转载自www.cnblogs.com/1175429393wljblog/p/13403387.html