mongodb - 什么时候应该在 MongoDB 中设置 TTL 索引?

标签 mongodb indexing ttl

我想为 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/

相关文章:

mysql - 使 MySQL 为查询选择最佳索引

apache-spark - 从具有不同 TTL 的 Spark 在 Cassandra 上批量插入

linux - 如何关闭 BeagleBone Black Wireless 上的 GPIO 端口

c - MongoDB、ZeroMQ 和 C

javascript - Meteor:变量随机设置为 NaN

甲骨文 SQL : Single Index with two Columns vs index on one Column

c# - 获取控制数组中的控制索引

python - 没有收到所有 ICMP 超时消息 : why?

node.js - 是否可以在 Express 中使特定用户的 session 数据无效或删除?

mongodb - 发生异常。 MongoDartError (MongoDart 错误 : Invalid scheme in uri: mongodb+srv://) with flutter