MongoDB中设置expire过期自动删除

关键词: expireAfterSeconds、TTL

TTL Time to Live

 

类似Redis中的expire机制,MongoDB也可以设置过期自动删除的表。

MongoDB的过期设置依赖索引(TTL-index),设置过期字段使用的索引后,插入数据时在该字段指定日期时间,

经过在创建索引时指定的秒数后,该记录会被MongoDB认为已经过期,然后删除。

 

JS版

db.test_timer.createIndex({"timer":1}, {expireAfterSeconds: 10})
db.test_timer.insert({"timer":new Date(), "a":'abc'})  // 指定当前时间
db.test_timer.insert({"timer": new Date("2017/3/25 13:11:00"), "c": "CC"})  // 指定任意时间

 

Python版

创建索引和指定过期时间的方式类似,要注意的是过期时间的字段必须使用UTC时间,否则无法正常删除记录
因此指定过期时间删除虽然也可以起作用,但是不能确定删除时间非常精确。

from pymongo import MongoClient
cli = MongoClient()
db = cli['test']
tbl = db['test_timer2']
tbl.create_index([("timer2", 1)], expireAfterSeconds=10)
from datetime import datetime
tbl.insert({"timer2": datetime.utcnow(), "user": "Hehehehe!"})

from time import strptime, time, mktime
t1 = strptime("2017/3/25 13:36:02", "%Y/%m/%d %H:%M:%S")
t2 = datetime.utcfromtimestamp(mktime(t1))
tbl.insert({"timer2": t2, "CC": 12345})
tbl.insert({"timer2": 123, "TT": 1})  # TTL-index字段也可以是其他值,这是就不能被自动删除
cli.close()

 

经过测试,实际删除数据的时间与索引加上数据指定的时间点之间存在偏移,可能是MongoDB删除数据机制的问题。

转载于:https://my.oschina.net/u/200350/blog/1492900

在Spring Boot中设置MongoDB自动过期时间并自动删除数据可以通过设置TTL(Time To Live)索引来实现。 TTL索引是一种设置文档过期时间的方法,它允许我们在MongoDB设置一个特定的时间,在这个时间之后,该文档将被自动删除。 首先,我们需要在MongoDB的集合中创建一个TTL索引。假设我们想要将过期时间设置为24小时,我们可以执行以下操作: 1. 在对应的MongoDB集合中创建TTL索引,可以使用以下命令: ```java db.myCollection.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 86400 }) ``` 以上命令中的`myCollection`是集合的名称,`createdAt`是字段的名称,`expireAfterSeconds`是过期时间。 2. 在Spring Boot项目中使用MongoDB的Java驱动程序,添加以下依赖项: ```java <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> ``` 3. 创建一个实体类来映射MongoDB的文档,例如: ```java @Document(collection = "myCollection") public class MyDocument { @Id private String id; private String data; private Date createdAt; // getters and setters } ``` 4. 在Spring Boot的配置类中,使用@EnableMongoRepositories注解开启MongoDB的Repository功能。 5. 创建一个MongoDB的Repository接口,通过继承MongoRepository接口,例如: ```java public interface MyDocumentRepository extends MongoRepository<MyDocument, String> { } ``` 6. 在业务逻辑中使用MyDocumentRepository操作数据库,例如: ```java @Autowired private MyDocumentRepository myDocumentRepository; public void saveDocument(MyDocument document) { document.setCreatedAt(new Date()); myDocumentRepository.save(document); } ``` 通过以上步骤的设置,当往集合中插入文档时,MongoDB自动设置并计算过期时间,并在过期时间到达后自动删除该文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值