2014-09-24 101 views
1

我在Mongo 2.4.10上使用TTL索引,但它不再工作。例如,在一個收集,我已經將它設置爲5天(432000秒),我們可以用db.collectionName.getIndexes()參見:mongodb背景TTL不刪除文件

{ 
      "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") 

Java代碼來創建TTL指標如下:

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 } 

回答

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); 

注意,您需要先手動刪除現有的索引,然後才能重新添加它。