使用php在mongodb中的某个时钟时间使文档过期
我的php中有以下代码:使用php在mongodb中的某个时钟时间使文档过期,php,mongodb,Php,Mongodb,我的php中有以下代码: $m = new MongoClient(); $db = $m->selectDB('authentication'); $collection = new MongoCollection($db, 'digits'); $document = array( "username" => $_POST['username'], "digits" => $_POST['digits']
$m = new MongoClient();
$db = $m->selectDB('authentication');
$collection = new MongoCollection($db, 'digits');
$document = array(
"username" => $_POST['username'],
"digits" => $_POST['digits']
);
$collection->insert($document);
我想这些文件被删除后2小时自动使用ttl功能的mongodb。
每分钟可能会插入数千个文档,所以我不希望它们变得凌乱或有问题,我希望它们在同一个集合中独立删除。
如果你能用php编写代码,我将不胜感激。因为在其他地方,他们只是直接解释mongodb命令,我不明白如何在php中使用它。谢谢
编辑1:
在“Christian P”的帮助下,我创建了30个测试文档:
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);
}
编辑2:
正如“Christian P”在他的编辑中所说,“expireAfterSeconds”应该作为数组传递。要通过设置TTL自动从集合中删除,您必须做两件事:
日期
字段$document = [
"username" => $_POST['username'],
"digits" => $_POST['digits'],
"createdAt" => new MongoDate()
];
和其他常规索引一样,可以使用命令添加TTL索引
$collection->ensureIndex(
['createdAt' => 1], ['expireAfterSeconds' => 7200]
);
上述命令将在createdAt
上添加一个索引TTL index,该索引将在2小时后删除文档 要通过设置TTL自动从集合中删除,必须执行两项操作:
日期
字段$document = [
"username" => $_POST['username'],
"digits" => $_POST['digits'],
"createdAt" => new MongoDate()
];
和其他常规索引一样,可以使用命令添加TTL索引
$collection->ensureIndex(
['createdAt' => 1], ['expireAfterSeconds' => 7200]
);
上述命令将在
createdAt
上添加一个索引TTL index,该索引将在2小时后删除文档 @ThomasRuiz:不,我不是说全部密码。我的意思是像我自己一样从$m=新MongoClient();到$collection->insert($document);不会超过10行。@ThomasRuiz:不,我不是说全部代码。我的意思是像我自己一样从$m=新MongoClient();到$collection->insert($document);不会超过10行。我不知道MongoDate(),谢谢。我意识到mongodb的时区是-1 UTC,服务器的时间是-8 UTC。我将windows服务器的时区更改为-1UTC,对于测试,我将ttl更改为20秒,然后重试。现在,它们正在正确的时间插入,但仍然没有发生任何事情。即使超过五分钟也没有删除任何一个。@MDP抱歉,我的错误:/I键入的速度太快,没有将索引的选项添加为数组,因此创建了常规索引。查看我的编辑。我不知道MongoDate(),谢谢。我意识到mongodb的时区是-1 UTC,服务器的时间是-8 UTC。我将windows服务器的时区更改为-1UTC,对于测试,我将ttl更改为20秒,然后重试。现在,它们正在正确的时间插入,但仍然没有发生任何事情。即使超过五分钟也没有删除任何一个。@MDP抱歉,我的错误:/I键入的速度太快,没有将索引的选项添加为数组,因此创建了常规索引。请参阅我的编辑。