Expire Documents at a Certain Clock Time in mongodb with php -
Expire Documents at a Certain Clock Time in mongodb with php -
i have code within php:
$m = new mongoclient(); $db = $m->selectdb('authentication'); $collection = new mongocollection($db, 'digits'); $document = array( "username" => $_post['username'], "digits" => $_post['digits'] ); $collection->insert($document);
i want these documents deleted after 2 hours automatically using ttl feature of mongodb. there may thousands of documents inserting every minute, don't want them messy or buggy, want them deleted independently in same collection. if can set code in php i'd appreciate it. because everywhere else explained mongodb commands directly, couldn't understand how utilize in php. thanks.
edit 1: help of "christian p", created 30 documents test:
for($i=0;$i<30;$i++){ $m = new mongoclient(); $db = $m->selectdb('authentication'); $collection = new mongocollection($db, 'teeeest'); $collection->ensureindex(array('createdat' => 1, 'expireafterseconds' => 60)); $document = array( "username" => "4563678678", "digits" => "5958974", "createdat" => new mongodate() ); $collection->insert($document); sleep(1); }
but not beingness removed. illustration of created documents:
{ "_id": { "$oid": "53ac7c237fae31100e000109" }, "username": "4563678678", "digits": "5958974", "createdat": { "$date": "2014-06-26t20:01:39.000z" } } { "_id": { "$oid": "53ac7c247fae31100e00010a" }, "username": "4563678678", "digits": "5958974", "createdat": { "$date": "2014-06-26t20:01:40.000z" } } { "_id": { "$oid": "53ac7c257fae31100e00010b" }, "username": "4563678678", "digits": "5958974", "createdat": { "$date": "2014-06-26t20:01:41.000z" } }
edit 2: "christian p" said in edit, "expireafterseconds" should passed array.
to automatically expire data collection setting ttl must 2 things:
createdate
field. insert this: create ttl index on field to create date field in php need utilize mongodate object:
$document = array( "username" => $_post['username'], "digits" => $_post['digits'], "createdat" => new mongodate() );
you can add together ttl index using ensureindex command, other regular indexes.
$collection->ensureindex(array('createdat' => 1), array('expireafterseconds' => 7200));
the above command add together index ttl index on createdat
delete documents after 2 hours.
php mongodb
Comments
Post a Comment