Auto-delete documents when expired on MongoDB
mongodb, php
Solution
To expire documents after a certain number of seconds, you can create a TTL index that is a special index property that relies on a background thread in mongod that reads the target index date values and performs delete operations on those who have expired.
To do this you will need a createdAt field that stores the insertion date in your log collection, for example you can use "new Date()”
To enable TTL for a collection use ensureIndex() method to create an index with the expireAfterSeconds additional property.
db.log.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
This statement will create a TTL index and MongoDB will automatically delete documents from log collections when the createdAt value is older than the createdAt value + expireAfterSeconds value (3600 = 60secs * 60 mins).
The background task that removes expired documents runs every 60 seconds
I also recommend you to take a look to the following article that explains exactly the full process: http://mongodbspain.com/en/2014/02/08/expire-data-from-collections-using-ttl/
Regards.
Problem
I'm developing a PHP application that stores a historical log in a MongoDB collection. After 1 hour, these data are not important and are deleted by a CRON process that runs every hour. The question is, is there any other solution to remove these documents automatically after a period of time since its insertion? Thank you very much!