mongodb는 ttl(생명 주기)를 두가지 방식으로 설정할 수 있다.


1. collection 단위로 ttl을 주어, collection에 저장되는 모든 document에 ttl이 자동으로 설정되게 한다.


아래 예제는 local db 밑에 location이라는 collection을 생성 후, 60초 뒤에 자동삭제를 하도록 한다. 


$ mongdb


replset:PRIMARY> use local

replset:PRIMARY> db.location.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 60 } )

replset:PRIMARY> db.location.insert( {

   "createdAt": new Date(),

   "id": 1,

   "url" : "http://map.google.com/12312"

} )




2. document 단위로 ttl을 준다.


아래 예제는 local db 밑에 google이라는 collection을 생성 후, 다큐먼트가 2015년 9월 22일 14시에 자동삭제를 하도록 한다. index 생성시 expireAfterSeconds는 expireAt시간 이후의 삭제할 시간을 명세할 수 있다. 


replset:PRIMARY> use local

replset:PRIMARY>  db.google.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )

replset:PRIMARY>  db. google.insert( {

   "expireAt": new Date('9 22, 2015 14:00:00'),

   "id": 2,

   "url": "http://map.google.com/12313"

} )


자바의 mongo-jpa를 이용해서 구현할 때, class를 다음과 같이 디자인하여 expireTiime을 두어 TTL을 가진 캐시 item을 생성할 수 있다. 

@JsonIgnoreProperties(ignoreUnknown = true)
public class Google {
@Id
private String id;
private String url;
private Date expireAt = DateUtils.addMinutes(new Date(), 1); // getter, setter }


또한 터미널에서 실제 데이터가 언제 데이터가 사라지는지 확인하기 위한 방법은 두가지가 있다.

1. db.collection.find()를 수동으로 실행하면서 체크하기

2. 자바 스크립트로 데이터가 확인하기


// 아무 것도 없으면 그냥 종료

replset:PRIMARY> var startDate = new Date(); while (true) { var count = db.location.count(); print ("Documents : " + count + "( " + (new Date() - startDate) + " ms)"); if (count == 0) break; sleep(5000); }

Documents : 0( 1 ms)


// 1분뒤에 삭제되는 데이터 추가

replset:PRIMARY> var startDate = new Date(); while (true) { var count = db.googleLocation.count(); print ("Documents : " + count + "( " + (new Date() - startDate) + " ms)"); if (count == 0) break; sleep(5000); }

Documents : 1( 1 ms)

Documents : 1( 5002 ms)

Documents : 1( 10003 ms)

Documents : 1( 15004 ms)

Documents : 1( 20004 ms)

Documents : 1( 25005 ms)

Documents : 1( 30006 ms)

Documents : 1( 35007 ms)

Documents : 1( 40008 ms)

Documents : 1( 45009 ms)

Documents : 1( 50009 ms)

Documents : 1( 55010 ms)

Documents : 1( 60012 ms)

Documents : 1( 65013 ms)

Documents : 1( 70014 ms)

Documents : 1( 75015 ms)

Documents : 1( 80016 ms)

Documents : 1( 85017 ms)

Documents : 1( 90018 ms)

Documents : 1( 95019 ms)

Documents : 1( 100019 ms)

Documents : 0( 105020 ms)






* 주의할 점

collection 단위로 ttl을 줄 때는 "createdAt"(과거형)이고, document 단위는 "expireAt" (현재형)이다. 

expiredAt 이 아님..







참고

http://docs.mongodb.org/manual/tutorial/expire-data/

http://www.codeproject.com/Tips/467689/MongoDB-Time-To-Live-TTL-Collections

Posted by '김용환'
,