FS1360472174 / nosql-mongo

mongo knowledge
4 stars 4 forks source link

mongot ttl #18

Closed FS1360472174 closed 7 years ago

FS1360472174 commented 7 years ago

https://docs.mongodb.com/v3.2/tutorial/expire-data/

FS1360472174 commented 7 years ago

创建一个TTL index,然后设置一个过期时间expireAfterSeconds

1.db.log.createIndex({updateDate:1},{expireAfterSeconds:3600}) 3600s后数据过期, If the field is an array, and there are multiple date values in the index, MongoDB uses lowest (i.e. earliest) date value in the array to calculate the expiration threshold. https://docs.mongodb.com/v3.2/core/index-ttl/

是array,取最早的时间。即只要有一个过期,就过期 2.或者.db.log.createIndex({updateDate:1},{expireAfterSeconds:0}) 然后设置每个document的过期时间

db.log.insert({ "updateDate“: new Date('过期绝对时间') })

3.delete 操作 后台进程去读ttl index值,然后移除值。可以通过db.currentOp()来查看到

4.index build好以后,就开始deleting documents 过期的数据并不会马上被删除, background 的task每隔60s run一次。

5.在一个复制集中 TTL 后台进程只会run在primary 节点。然后复制删除操作到secondary节点上

限制 1.不能在capped collection(固定size)创建ttl 2.不能更改expireAfterSeconds, 需要先删除,然后重新创建 3.如果一个字段上已经有index了,不能在这个字段上再创建一个 ttl index.需要先删除,再创建