使用php在mongodb中的某个时钟时间到期文档

时间:2014-06-26 15:58:53

标签: php mongodb

我在php中有这个代码:

    $m = new MongoClient();
    $db = $m->selectDB('authentication');
    $collection = new MongoCollection($db, 'digits');
    $document = array( 
        "username" => $_POST['username'], 
        "digits" => $_POST['digits']
        );
    $collection->insert($document);

我希望在使用mongodb的ttl功能2小时后删除这些文档。 每分钟可能会插入数千个文档,因此我不希望它们变得混乱或错误,我希望它们可以在同一个集合中独立删除。 如果你可以把代码放在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);
    }

但他们没有被删除。 创建文档的示例:

{
    "_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"
    }
}

编辑2: as&#34; Christian P&#34;在他的编辑中说,&#34; expireAfterSeconds&#34;应该作为数组传递。

1 个答案:

答案 0 :(得分:3)

要通过设置TTL从集合中自动expire data,您必须做两件事:

  1. 创建Date字段。
  2. 在该字段上创建TTL索引。
  3. 要在PHP中创建Date字段,您需要使用MongoDate对象:

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

    您可以使用ensureIndex命令添加TTL索引,作为其他常规索引。

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

    上述命令将在createdAt上添加一个索引TTL索引,该索引将在2小时后删除文档。