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

如何将指定删除租户历史数据的SQL语句转换为MongoDB语句

SQL转MongoDB删除语句实现方案

对齐原SQL实现逻辑:按租户分组,删除每个租户日期小于当前日期减30天且早于该分组内最大日期的所有记录。


实现步骤

1. 定义30天阈值日期

// 计算当前日期往前推30天的时间节点
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - 30);

2. 聚合查询各租户对应阈值前的最大日期

const tenantMaxDateList = db.collection.aggregate([
  // 先过滤所有早于30天阈值的记录,缩小聚合范围
  { $match: { date: { $lt: cutoffDate } } },
  // 按租户ID分组,取分组内最大的日期值
  { $group: {
    _id: "$tenantid",
    groupMaxDate: { $max: "$date" }
  } }
]).toArray();

3. 执行删除操作

普通循环删除(适合数据量较小的场景)

tenantMaxDateList.forEach(tenant => {
  db.collection.deleteMany({
    tenantid: tenant._id,
    date: { $lt: tenant.groupMaxDate }
  });
});

批量操作(MongoDB 4.2+ 推荐,性能更高)

const bulkDeleteOps = tenantMaxDateList.map(tenant => ({
  deleteMany: {
    filter: {
      tenantid: tenant._id,
      date: { $lt: tenant.groupMaxDate }
    }
  }
}));

// 批量执行所有删除操作
db.collection.bulkWrite(bulkDeleteOps);

注意事项

执行删除前建议先执行下述统计语句,确认待删除的记录数符合预期,避免误删数据:

let totalDeleteCount = 0;
tenantMaxDateList.forEach(tenant => {
  const curTenantDeleteCount = db.collection.countDocuments({
    tenantid: tenant._id,
    date: { $lt: tenant.groupMaxDate }
  });
  totalDeleteCount += curTenantDeleteCount;
  console.log(`租户ID ${tenant._id} 待删除记录数:${curTenantDeleteCount}`);
});
console.log(`总待删除记录数:${totalDeleteCount}`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:06:05