M D P M D P - 3 months ago 21
PHP Question

Expire Documents at a Certain Clock Time in mongodb with php

I have this code inside my 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 to be deleted after 2 hours automatically using ttl feature of mongodb.
there may be thousands of documents inserting every minute, so I don't want them to get messy or buggy, I want them to be deleted independently in the same collection.
If you can put the code in php I'd appreciate it. because everywhere else they just explained mongodb commands directly, which I couldn't understand how to use it in php. thanks.

Edit 1:
with the help of "Christian P", I created 30 documents for 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 they are not being removed.
an example 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:
as "Christian P" said in his edit, "expireAfterSeconds" should be passed as an array.

Answer

To automatically expire data from collection by setting TTL you must do two things:

  1. Create a Date field.
  2. Create a TTL index on that field.

To create a Date field in PHP you need to use MongoDate object:

$document = [ 
    "username" => $_POST['username'], 
    "digits" => $_POST['digits'],
    "createdAt" => new MongoDate()
];

You can add a TTL index using ensureIndex command, as other regular indexes.

$collection->ensureIndex(
    ['createdAt' => 1], ['expireAfterSeconds' => 7200]
);

The above command will add an index TTL index on the createdAt that will delete documents after 2 hours.