tangbinde 发表于 2017-12-14 23:57:39

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删除数据机制的问题。
页: [1]
查看完整版本: MongoDB中设置expire过期自动删除