2

Since MongoDB 2.2 it is possible to "Expire Data from Collections Using a TTL" which is implemented as a special index type.

The latest version of Doctrine ORM supports this Index Option. Unfortunately I have not been able to find how to correctly set this index using doctrine annotations/config files.

This is how I'm attempting to do it, I hope some one can help me setting it correctly:

<?php 

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document(collection="log")
 * @MongoDB\Indexes({
 *      @MongoDB\Index(keys={"expiration"=1, "expireAfterSeconds"=30})
 *      //... other indexes go here
 * })
 * 
 */
class Log
{
    // ...

    /** 
     * @MongoDB\Date 
     */
    protected $expiration;

    // ... 
}

Then when I execute php app/console doctrine:mongodb:schema:update (in symfony 2.3.x) The index is generated, but the index generated doesn't look correct.

this is what I get when I execute db.system.indexes.find(); in my database:

{ "v" : 1, "key" : { "expiration" : 1, "expireAfterSeconds" : 30 }, "ns" : "mydatabase.log", "sparse" : false, "name" : "expiration_1_expireAfterSeconds_-1" }

which is not the same as if I create the index manually:

db.log.ensureIndex( { "expiration": 1 }, { expireAfterSeconds: 30 } );

as it generates the following index:

{ "v" : 1, "key" : { "expiration" : 1 }, "ns" : "mydatabase.log", "name" : "expiration_1", "expireAfterSeconds" : 30 }

How would I setup TTL on a date field using doctrine annotations/config files?

4

1 回答 1

3

您正在将索引选项与keys参数混合。Index注释也有一个options参数。请参阅索引注释文档中的示例:

<?php

/**
 * @Document(
 *   indexes={
 *     @Index(keys={"username"="desc"}, options={"unique"=true})
 *   }
 * )
 */
class User
{
    //...
}

这相当于{unique: true}作为第二个参数传递db.collection.ensureIndex()。您可以替换uniqueexpireAfterSeconds创建 TTL 索引。

于 2013-08-23T21:27:17.023 回答