我使用MongoDB(v3.4)作为缓存并使用TTL索引使记录失效 . 但是,TTL设置似乎无法正常工作 . 具体来说,我使用 endpoints 测试插入数据(如下所示) .
endpoints mongoInsert应该在5分钟后到期 . 然而,似乎在约1分钟后,文件被删除 . 我已经使用moment() . utc() . toDate()查找了有关使用UTC时间的其他类似建议,并且行为是相同的 . 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);
});
})
})
}
}
1 回答
和
这是无效的
您不能使用createIndex()来更改现有索引的expireAfterSeconds值 . 而是将collMod数据库命令与索引集合标志结合使用 . 否则,要更改现有索引的选项的值,必须先删除索引并重新创建 .
https://docs.mongodb.com/v3.4/core/index-ttl/
对于单个文档的到期,有报告称只能通过计算到期时间并按特定时钟时间到期(ref:groups.google.com/forum/#!topic/mongodb-dev/ZLb8KSrLyOo)来完成 .