You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Cron定时任务删除MongoDB集合中2年以上的历史记录?

实现方案

你只需要动态计算2年前对应的秒级Unix时间戳阈值,和latest_event_time字段直接比较即可完成删除,无需修改字段类型。

1. 核心删除逻辑

latest_event_time存储的是秒级Unix时间戳(double类型),我们通过Date对象动态计算2年前的时间戳阈值,避免固定秒数导致的闰年/大小月误差:

// 计算2年前对应的秒级时间戳
const twoYearsAgo = new Date();
twoYearsAgo.setFullYear(twoYearsAgo.getFullYear() - 2);
const thresholdTimestamp = twoYearsAgo.getTime() / 1000;

// 先查询匹配的记录数,确认数量符合预期再执行删除
db.你的集合名.countDocuments({
  latest_event_time: { $lt: thresholdTimestamp }
})

// 执行删除操作
db.你的集合名.deleteMany({
  latest_event_time: { $lt: thresholdTimestamp }
})

如果集合数据量较大,建议先给latest_event_time加索引提升执行效率:

db.你的集合名.createIndex({ latest_event_time: 1 })

2. 配置Cron定时任务

第一步:编写执行脚本

新建clean_expired_records.js文件,填入完整的连接和执行逻辑:

// 替换为实际的MongoDB连接地址、账号密码、库名
const mongoConn = new Mongo("mongodb://账号:密码@127.0.0.1:27017/目标库名?authSource=admin");
const db = mongoConn.getDB("目标库名");

// 计算阈值
const twoYearsAgo = new Date();
twoYearsAgo.setFullYear(twoYearsAgo.getFullYear() - 2);
const thresholdTimestamp = twoYearsAgo.getTime() / 1000;

// 执行删除
const deleteRes = db.你的集合名.deleteMany({ latest_event_time: { $lt: thresholdTimestamp } });
// 输出日志便于排查
print(`[${new Date().toLocaleString()}] 成功删除过期记录:${deleteRes.deletedCount} 条`);

第二步:配置定时任务

执行crontab -e编辑定时任务,添加如下配置(示例为每天凌晨2点执行一次,可按需调整执行频率):

0 2 * * * /usr/bin/mongosh /path/to/clean_expired_records.js >> /path/to/clean_record.log 2>&1

注意:如果使用的是旧版本MongoDB,将mongosh替换为mongo即可,二进制路径以实际安装路径为准。


内容的提问来源于stack exchange,提问作者Abhilash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 18:18:01