在特定时间删除MongoDB文档

saf*_*yeh 10 mongoose mongodb node.js

我期待在特定时间删除文档.

const TestSchema = new Schema({
 expire_at: {
 type: Date,
 },
}, {
 timestamps: true,
});
TestSchema.index({expire_at: 1}, {expireAfterSeconds: 0});
Run Code Online (Sandbox Code Playgroud)

POST

const test = new TestSchema(this.request.body);
  test.expire_at = test.end_time;

  try {
    yield test.save();
  } catch (error) {
    this.status = 409;
    this.response.body = error.errors;
    return;
  }

  this.response.body = test;
  this.status = 201;
Run Code Online (Sandbox Code Playgroud)

似乎文件在expire_at中指定的时间删除.

我使用的是这种日期格式:2016-07-20T05:01:19.567Z

emi*_*svz 17

这将在两小时内删除文档:

const TestSchema = new Schema({
    expire_at: {type: Date, default: Date.now, expires: 7200} 
})

//expired in 2 hours
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!这有效。我尝试了很多变体和组合,包括与“createdAt”完全相同的模式,但是从未起作用。但这有效! (2认同)

Sha*_*Roy 8

要在特定时间删除MongoDB文档,您可以使用TTL(生存时间).TTL索引是特殊的单字段索引,MongoDB可以使用它在一定时间后自动从集合中删除文档.

所以你需要创建一个TTL索引,如:(mongo shell命令)

db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
Run Code Online (Sandbox Code Playgroud)

或者您可以使用mongoose来创建此索引

TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
Run Code Online (Sandbox Code Playgroud)

然后mongodb每隔60秒检查一次,如果expire_at日期时间小于当前日期时间,那么此记录将在5秒后删除.

TTL索引不保证在到期时立即删除过期数据.文档到期的时间与MongoDB从数据库中删除文档的时间之间可能存在延迟.

删除过期文档的后台任务每60秒运行一次.结果,文档可能在文档到期和后台任务运行之间的期间保留在集合中.

TTL指数

注意:使用createIndex而不是index


小智 5

删除过程在 60 秒后运行。所以文档可以在删除时间过去后保留 59 秒。