我正在使用mongodb(v3.4)作为缓存,并使用ttl索引到期记录。但是,TTL设置似乎无法正常工作。具体来说,我使用端点插入数据进行了测试(如下)。
端点蒙古斯应该在5分钟内到期。但是,似乎在约1分钟后,该文档被删除了。我查看了有关使用Moment()的UTC时间使用UTC()。todate()的其他类似建议,行为是相同的。new Date()返回UTC时间,所以我想它应该是相同的效果。
不确定是否还应包括其他设置,但文档中未详细介绍。有人以前遇到过吗?
function mongoInsert(mongoClient){
return function(req, res){
mongoClient.connect('mongodb://localhost:27017/cache', function(err, db) {
db.collection('data', function(err, collection){
var testItems = [{
"_id": "abc12345",
"dmac": "abc",
"createdAt": new Date(),
"val": {
"0": 10,
"1": 15,
"2": 5
},
"res": "minutes",
"time": "2017-12-04T00:12:58Z"
}];
let unix = new moment().valueOf();
collection.createIndex({createdAt: unix}, {expireAfterSeconds: 300});
collection.insertMany(testItems, function(err, items){
db.close();
res.json(items);
});
})
})
}
}
collection.createIndex({createdAt: 1}, {expireAfterSeconds: 60,unique:true});
和
collection.createIndex({createdAt: 1}, {expireAfterSeconds: 300,unique:true});
这是无效的
您不能使用CreateIndex()更改现有索引的ExefterSeconds的值。而是将CollMod数据库命令与索引集合标志结合使用。否则,要更改现有索引选项的值,您必须先删除索引并重新创建。
https://docs.mongodb.com/v3.4/core/index-ttl/
对于各个文档到期的有报道说,只能通过计算到期时间并在特定时钟时间到期来完成(ref:groups.google.com/forum/# !! topic/mongodb-dev/zlb8ksrlyoo)。
var testItems = [{
"_id": "abc12345",
"dmac": "abc",
"expireAt": moment().add(3, 'minutes').toDate(),
"val": {
"0": 10,
"1": 15,
"2": 5
},
"res": "minutes",
"time": "2017-12-04T00:12:58Z"
}];
let unix = new moment().valueOf();
collection.createIndex({expireAt: unix}, {expireAfterSeconds: 0}, function(error, indexName){
if(error) console.log(error);
console.log(indexName);
});