MongoDB의 collection에서
document가 자동으로 삭제되도록 설정하고 싶다. 이러한 상황에서 활용할 수 있는 것이 TTL(Time To Live)이다.
db.getCollection('rooms').createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400, partialFilterExpression: { numberOfPeopleInRoom: { $lt: 1 } } }
)
Robo3T 등을 활용하여 위와 같이 MongoDB 명령어를 입력한다.
rooms라는 collection에서 createdAt을 기준으로 24시간이 지나고, numberOfPeopleInRoom의 값이 1보다 작다면 document가 삭제되도록 설정할 수 있다.
해당 index 설정은 아래 명령어로 확인할 수 있다.
db.getCollection('rooms').getIndexes()
해당 index 설정을 삭제하는 명령어는 다음과 같다.
db.getCollection('rooms').dropIndex({ createdAt: 1 })
삭제한 이후에는 다시 변경할 index 설정을 입력할 수 있다.