【问题标题】:Why mongodb doesn't delete document every 30 seconds?为什么mongodb不每30秒删除一次文档?
【发布时间】:2021-07-14 14:14:56
【问题描述】:

我在为 mongodb 使用 typegoose 实现 TTL 时遇到问题。 基本上我想从集合中删除超过 30 秒的文档。

@ObjectType("TokenResetPasswordType")
@InputType("TokenResetPasswordInput")
@index(
   { createdAt: -1, confirmed: 1 },
   { expireAfterSeconds: 30, partialFilterExpression: { confirmed: false } }
)
export class TokenResetPassword {
    @Field()
    @Property({ lowercase: true, required: true, unique: true })
    email: string;

    @Field(() => [User], { nullable: true })
    @Property({ ref: "User", default: "" })
    user?: Ref<User>;

    @prop({ default: Date.now, index: true })
    createdAt?: Date;
}

【问题讨论】:

  • 请分享更多代码。我们现在对您的问题无能为力。
  • 检查存储在 MongoDB 中的实际索引。如果代码运行时集合和索引已经存在,mongoose 将删除并重新创建索引。

标签: node.js mongodb typescript typegoose


【解决方案1】:

https://docs.mongodb.com/manual/core/index-ttl/

TTL 索引是特殊的单字段索引,MongoDB 可以使用它在一定时间或特定时钟时间后自动从集合中删除文档。

您需要单独为createdAt 字段创建expireAfterSeconds 索引,而不是同时为两个字段。

另请注意:

https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation

删除操作的时机

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

删除过期文档的后台任务每 60 秒运行一次。因此,在文档过期和后台任务运行期间,文档可能会保留在集合中。

由于删除操作的持续时间取决于您的 mongod 实例的工作负载,因此过期数据可能会在后台任务运行之间的 60 秒周期之外存在一段时间

【讨论】:

  • 等了10分钟,数据还在
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2012-06-13
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多