1

我在 Mongo 2.4.10 上使用 TTL 索引,但它不再起作用了。例如,在一个集合中,我将其设置为 5 天(432000 秒),正如我们在 db.collectionName.getIndexes() 中看到的那样:

    {
            "v" : 1,
            "key" : {
                    "date" : -1,
                    "background" : true,
                    "expireAfterSeconds" : 432000
            },
            "ns" : "dbName.collectionName",
            "name" : "date_-1_background__expireAfterSeconds_432000"
    }

但是一个 findOne() 向我显示了一个比预期更旧的文档:

    "_id" : ObjectId("53a058140cf25876d78f7d03"),
    "_class" : 
    "productIds" : [
            NumberLong(1045),
            NumberLong(1124),
            NumberLong(1277),
            NumberLong(800),
            NumberLong(978)
    ],
    "userId" : NumberLong(214120),
    "date" : ISODate("2014-06-16T11:45:21.341Z")

创建 TTL 索引的 java 代码如下:

    DBObject keys = new BasicDBObject();
    keys.put(fieldName, -1);
    keys.put("background", true);
    keys.put("expireAfterSeconds", ttlInSeconds);

    database.getCollection(collectionName).ensureIndex(keys);

直到最近,一切似乎都运行良好:我们之前在生产中没有注意到它。这发生在我所有的数据库和所有相关的集合上。

怎么了 ?


编辑

我检查了我的服务器配置,启用了 TTL 监视器:

my_replicat:PRIMARY> db.adminCommand({getParameter:1, ttlMonitorEnabled:1 })
{ "ttlMonitorEnabled" : true, "ok" : 1 }
4

1 回答 1

3

您正在添加backgroundexpireAfterSeconds作为索引的附加字段,而不是作为索引选项。将它们放在第二个DBObject参数中ensureIndex

DBObject keys = new BasicDBObject();
keys.put(fieldName, -1);

DBObject options = new BasicDBObject();
options.put("background", true);
options.put("expireAfterSeconds", ttlInSeconds);

database.getCollection(collectionName).ensureIndex(keys, options);

请注意,您需要先手动删除现有索引,然后才能重新添加它。

于 2014-09-24T16:08:12.273 回答