发布于 2015-09-14 14:49:26 | 213 次阅读 | 评论: 0 | 来源: 网络整理
2.2 新版功能.
This document provides an introductions to MongoDB’s “time to live” or “TTL” collection feature. Implemented as a special index type, TTL collections make it possible to store data in MongoDB and have the mongod automatically remove data after a specified period of time. This is ideal for some types of information like machine generated event data, logs, and session information that only need to persist in a database for a limited period of time.
Collections expire by way of a special index that keeps track of insertion time in conjunction with a background thread in mongod that regularly removes expired documents from the collection. You can use this feature to expire data from replica sets and sharded clusters.
Use the expireAfterSeconds option to the ensureIndex method in conjunction with a TTL value in seconds to create an expiring collection. TTL collections set the usePowerOf2Sizes collection flag, which means MongoDB must allocate more disk space relative to data size. This approach helps mitigate the possibility of storage fragmentation caused by frequent delete operations and leads to more predictable storage use patterns.
注解
When the TTL thread is active, you will see a delete operation in the output of db.currentOp() or in the data collected by the database profiler.
Consider the following limitations:
注解
TTL indexes expire data by removing documents in a background task that runs once a minute. As a result, the TTL index provides no guarantees that expired documents will not exist in the collection. Consider that:
To set a TTL on the collection “log.events” for one hour use the following command at the mongo shell:
db.log.events.ensureIndex( { "status": 1 }, { expireAfterSeconds: 3600 } )
The status field must hold date/time information. MongoDB will automatically delete documents from this collection once the value of status is one or more hours old.
The TTL background thread only runs on primary members of replica sets. Secondaries members will replicate deletion operations from the primaries.