为什么 mongodb 不是每 30 秒删除一次文档?

Why mongodb doesn't delete document every 30 seconds?

我在为 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;
}

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

TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time.

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

另请注意:

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

Timing of the Delete Operation

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.

The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.

Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.