MongoDB什么时候设置TTL索引?

When should I set TTL index in MongoDB?

我想为会话集合使用 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 以获得更详细的讨论。

创建TTL索引时,不需要做额外的事情。 只需插入文档并等待终止。

如果您需要延长文档生命周期,请相应地更新 ttl 索引字段。

如果文档不包含索引字段,则文档不会过期。