mongodb TTL无法正常工作

时间:2015-01-16 03:10:42

标签: mongodb

我已执行此命令在mongodb上设置TTL索引, db.sessions.ensureIndex({'expiration':1},{“expireAfterSeconds”:30})

但是4天后,我发现这些文件没有删除。 我确认命令和文件的字段是正确的。

我不知道如何解决它。

执行db.serverStatus()之后,我得到了 localTime是2015-01-16 11:03:05.554 + 08:00

以下是我的收藏品的一些信息

db.sessions.getIndexes()

{
"0" : {
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "meta.sessions"
},
"1" : {
    "v" : 1,
    "key" : {
        "expiration" : 1
    },
    "name" : "expiration_1",
    "ns" : "meta.sessions",
    **"expireAfterSeconds" : 30**
}
}

db.sessions.find()

/* 0 */
{
    "_id" : ObjectId("54b4c2e0f840238ca1436788"),
    "data" : ...,
    "expiration" : **ISODate("2015-01-13T16:02:33.947+08:00"),**
    "sid" : "..."
}

/* 1 */
{
    "_id" : ObjectId("54b4c333f840238ca1436789"),
    "data" : ...,
    "expiration" : ISODate("2015-01-13T16:06:56.942+08:00"),
    "sid" : ".."
}
/* ... */

2 个答案:

答案 0 :(得分:5)

要使集合中的数据到期(在3.2版中测试),您必须创建索引:

db.my_collection.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

之后,您在此集合中插入的每个文档都必须具有" createdAt"与当前日期:

    db.my_collection.insert( {
   "createdAt": new Date(),
   "dataExample": 2,
   "Message": "Success!"
} )

当创建日期值+ expireAfterSeconds值到达时,文档将被删除。 注意:默认情况下,MongoDB中的后台任务每60秒发生一次。

答案 1 :(得分:3)

当您在前台创建TTL索引时(就像您一样),MongoDB会在索引完成构建后立即开始删除过期的文档。在索引创建期间最好tail -f mongod.log以跟踪进度。您可能希望删除&如果出现问题,重新创建索引。

如果索引是在后台创建的,那么TTL线程可以在构建索引时开始删除文档。

删除过期文档的TTL线程每60秒运行一次。

如果您在从副本集中取出并在独立模式下运行的副本上创建了索引,则会创建索引,但在重新加入(或删除副本集)配置之前,不会删除文档。如果是这种情况,您可以在mongod.log

中获得类似的内容

** WARNING: mongod started without --replSet yet 1 documents are ** present in local.system.replset ** Restart with --replSet unless you are doing maintenance and no other ** clients are connected. ** The TTL collection monitor will not start because of this. ** For more info see http://dochub.mongodb.org/core/ttlcollections

相关问题