Question

I am a beginner in mongoDB. I want to delete each message from my database after at least 30sec.

This is my code.

$mess = array(
    "login" => $_SESSION['name'],
    "message" => $_POST['msg'],
    "expire" => true
);

$db->chat->insert($mess);
$collection = $db->chat;
$collection->ensureIndex(array('expire' => true), array('expireAfterSeconds' => 30));
Was it helpful?

Solution

I don't know the gritty PHP syntax details, but the expire field must contain a date time, not a boolean. For instance, you could set the expire to now and rely on the 30s expireAfterSeconds. Alternatively, and more flexible, you can set the expire value to now +30s (that allows you to choose different timeouts per document).

Please be aware that the TTL function works using a monitoring thread that will check for expired documents every now and then. Don't expect it to be second precise (it's rather minute precise).

If your data is extremely short-lived and is used for a queue or something, you might want to take a look at capped collections and tailable cursors instead of TTL collections.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top