2014年2月12日 星期三

設定 MongoDB 中資料的存活時間(TTL)

自從 MongoDB 2.2 以後,開始支援一個算是常用的功能,可以直接在 collection 上設定資料的存活時間
例如假設插入一筆資料後,希望它在兩小時後自動消失,過去的作法是要自己實作 daemon 去檢查
不過在 MongoDB 2.2 開始,MongoDB 會幫忙做這件事,只要在 collection 上做好設定即可。

設定時,是透過 ensureIndex() 的方法設定索引,同時設定對這個索引值的 TTL
在官網 [1] 的設定語法範例如下:
db.log.events.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
上面的語法表示的是,MongoDB 會根據 "createdAt" 欄位顯示的時間為基準,讓資料在 3600 秒之後自動被刪除。

不過要注意的是,MongoDB 的實作是每分鐘做一次檢查,所以資料被刪除的時間並不會非常精準,會存在誤差在 1 分鐘之內。
另外官方文件中有提到一些限制,這些限制之下的資料是不會發生效用的,以下轉錄官方文件 [1] 中的限制:

  • The _id field does not support TTL indexes.
  • You cannot create a TTL index on a field that already has an index.
  • A document will not expire if the indexed field does not exist.
  • A document will not expire if the indexed field is not a date BSON type or an array of date BSON types.
  • The TTL index may not be compound (may not have multiple fields).
  • If the TTL field holds an array, and there are multiple date-typed data in the index, the document will expire when the lowest (i.e. earliest) date matches the expiration threshold.
  • You cannot create a TTL index on a capped collection, because MongoDB cannot remove documents from a capped collection.
  • You cannot use ensureIndex() to change the value of expireAfterSeconds. Instead use the collMod database command in conjunction with the index collection flag.
  • When you build a TTL index in the background, the TTL thread can begin deleting documents while the index is building. If you build a TTL index in the foreground, MongoDB begins removing expired documents as soon as the index finishes building.

參考資料:
1、Expire Data from Collections by Setting TTL
2、MongoDB 2.2 的 Time To Live (TTL) 集合

沒有留言: