在特定的时间删除MongoDB文档
我正在考虑在特定的时间删除文档。
const TestSchema = new Schema({ expire_at: { type: Date, }, }, { timestamps: true, }); TestSchema.index({expire_at: 1}, {expireAfterSeconds: 0});
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;
似乎并没有在expire_at中指定的时间删除文档。
我正在使用这个date格式:2016-07-20T05:01:19.567Z
这将在两个小时内删除文档:
const TestSchema = new Schema({ expire_at: {type: Date, default: Date.now, expires: 7200} }) //expired in 2 hours
要在特定的时间删除MongoDB文档,可以使用TTL(生存时间) 。 TTL索引是特殊的单字段索引,MongoDB可以在一段时间后使用它自动从集合中删除文档。
所以你需要创build一个TTL索引:(mongo shell命令)
db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
或者你可以用mongoose创build这个索引
TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );
然后每60秒检查一次mongodb,如果expire_at
date时间小于当前date时间,则该logging将在5秒后移除。
TTL索引不保证到期的数据将在到期后立即被删除。 文档到期和MongoDB从数据库中删除文档的时间之间可能会有延迟。
删除过期文档的后台任务每60秒运行一次。 因此,在文档到期和后台任务运行期间,文档可能会保留在一个集合中。
TTL索引
注意:使用createIndex
而不是index
删除过程在60秒后运行。 因此,在删除时间过后,文档可以在59秒内出现。
正如阿米特所说,TTL索引不能保证在到期时删除数据; 数据过期的后台任务将每60秒运行一次。
后台任务也会受到性能争夺和工作负载的影响,导致数据远远超出这个窗口:
删除过期文档的后台任务每60秒运行一次。 因此,在文档到期和后台任务运行期间,文档可能会保留在一个集合中。
由于删除操作的持续时间取决于您的mongod实例的工作负载,因此在后台任务运行之间的60秒时间内,过期的数据可能会存在一段时间。
资源