2016-01-29 55 views
4

我希望MongoDB在通过%秒后清除其集合中的数据。我正在设置索引,但收集不会在一段时间后被清除,所有文档仍然存在。MongoDB expireAfterSeconds不会删除文件

我在做什么错?

DB版本:3.2

设置索引:

db.collection('history').ensureIndex(
    { '_id': 1, 'created': 1 }, 
    { unique: true, background: true, w: 1, expireAfterSeconds: 60} 
); 

// or 

db.collection('history').createIndex(
    { '_id': 1, 'created': 1 }, 
    { unique: true, background: true, w: 1, expireAfterSeconds: 60} 
); 

// history document 
var _history = { 
    _id: new ObjectId(), 
    created: new Date() 
}; 

收藏历史,指数:

var historyCollectionIndex = [ 
    { 
     "v" : 1, 
     "key" : { 
      "_id" : 1 
     }, 
     "name" : "_id_", 
     "ns" : "guardian_dev.history" 
    }, 
    { 
     "v" : 1, 
     "unique" : true, 
     "key" : { 
      "_id" : 1, 
      "created" : 1 
     }, 
     "name" : "_id_1_created_1", 
     "ns" : "guardian_dev.history", 
     "background" : true, 
     "expireAfterSeconds" : 60 
    } 
] 

连接到创建索引的其他问题。

现在,可能发生两个条目具有相同的创建值,因此mongo现在抛出E11000重复键错误收集的错误。

是否可以添加created和expireAfterSeconds,但创建不一定是uniq?

+0

问题的第二部分:set unique:false – puppeteer701

回答

5

按照MongoDB site

的TTL指数是一个单一的场索引。复合索引不支持TTL属性。

如果删除_id: 1指数,而不是仅仅使用created那么它应该表现为你所期望

1

按照documentation的TTL指数是单场指数。复合索引不支持TTL属性。

db.collection('history').ensureIndex(
{'created': 1 }, 
{ unique: true, background: true, w: 1, expireAfterSeconds: 60} 
); 

我已经测试过它,这个指数,不像一个在你的问题,正确地清除出记录:您应该按如下方式创建索引。