如何更新集合上的TTL?

Run*_*tle 1 javascript mongodb node.js mongodb-query mongojs

使用NodeJS + MongoJS,我连接到mongo DB.

我在集合上设置了一个TTL:

myCollection.createIndex({createdAt: 1}, {expireAfterSeconds: 60 * 30})
Run Code Online (Sandbox Code Playgroud)

现在可以更新expireAfterSeconds的值吗?如果是这样,集合中现有项目的政策是什么,即:他们的TTL是自动更新还是未被触及?

Nei*_*unn 6

您实际上无法"更新"索引定义.你需要的是"删除"索引,然后"重新创建"它.所以.dropIndex()先使用

myCollection.dropIndex({ "createdAt": 1 },function(err,result) { });
Run Code Online (Sandbox Code Playgroud)

然后使用新的间隔重新创建:

myCollection.ensureIndex(
   { "createdAt": 1 },
   { "expireAfterSeconds": 60 * 10 },
   function(err,result) { }
);
Run Code Online (Sandbox Code Playgroud)

至于何时更新,mongod服务以每60秒的间隔运行一个事件,您处理删除任何项目,其中生效日期字段(即本例中的"createdAt")在当前时间的"到期时间"内服务器.

因此,这意味着删除索引并重新创建它并不重要,因为现有服务器进程将在每个具有在该间隔时钟上定义的索引的集合上运行相同的到期查询.


Ben*_*min 6

除了上面的@Neil 回答外,文档指出,

您不能用于createIndex()更改expireAfterSeconds现有索引的值。而是将collMod数据库命令与index集合标志结合使用。否则,要更改现有索引的选项值,您必须先删除该索引并重新创建。

所以

db.runCommand({
  "collMod": <collection>,
  "index": {
    keyPattern: <index_spec>,
    expireAfterSeconds: <seconds>
  }
})
Run Code Online (Sandbox Code Playgroud)

应该也能正常工作。