我想为 session 集合使用 TTL 索引。我的问题是我应该运行 db.collection.createIndex()
仅在服务器启动时运行一次,还是每次插入新文档后都必须运行该命令?
对于后一种情况,代码如下:
DB.findOneAndUpdate(args)
.then((result) => {
DB.createIndex({
'name': 'sessions',
'keys': {'lastLogin': 1},
'options': {expireAfterSeconds: req.session.cookie.maxAge}
});
})
.catch((err) => console.log(err));
最佳答案
My question is that should I run db.collection.createIndex() only once when the server starts, or do I have to run the command every time after inserting new document?
您不应在每次插入时指定 TTL 索引。在日期类型或 BSON 日期类型对象数组上创建索引,该索引将应用于每个文档。此外,您还可以使用 collMod
命令修改现有 TTL 索引的 expireAfterSeconds
。查看MongoDB documentation进行更详细的讨论。
关于mongodb - 什么时候应该在 MongoDB 中设置 TTL 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483365/