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

MongoDB如何批量更新_id存在于另一集合中的所有文档

方法1:Mongo Shell命令行实现(优先方案)

无需额外脚本,直接通过MongoDB自带的命令行工具即可完成操作:

  1. 若使用交互式Mongo Shell,连接到对应数据库后执行以下命令:
// 提取所有待更新的文档ID
const targetIds = db.docIdsToUpdate.distinct("docId");
// 批量更新匹配的文档
db.docs.updateMany(
  { _id: { $in: targetIds } },
  { $set: { deleted: true } }
);

执行后会返回更新结果,modifiedCount字段即为实际修改的文档数量。

  1. 若需要直接在系统终端执行无需进入Shell交互,可使用mongosh(老版本MongoDB用mongo命令)的--eval参数:
mongosh "mongodb://<你的数据库地址>:<端口>/<数据库名>" --eval 'const targetIds = db.docIdsToUpdate.distinct("docId"); db.docs.updateMany({ _id: { $in: targetIds } }, { $set: { deleted: true } });'

注意:请确保docIdsToUpdate集合中docId的字段类型和docs集合中_id的类型完全一致,否则会出现匹配失败的问题。

方法2:Node.js脚本(备选方案)

如果需要用Node.js实现,可参考以下代码:

  1. 先安装MongoDB Node.js驱动:
npm install mongodb
  1. 编写执行脚本:
const { MongoClient } = require('mongodb');

async function runUpdate() {
  // 替换为你的数据库连接串
  const client = new MongoClient('mongodb://<你的数据库地址>:<端口>');
  try {
    await client.connect();
    // 替换为你的数据库名
    const db = client.db('<数据库名>');
    // 提取待更新ID列表
    const targetIds = await db.collection('docIdsToUpdate').distinct('docId');
    // 执行更新
    const updateResult = await db.collection('docs').updateMany(
      { _id: { $in: targetIds } },
      { $set: { deleted: true } }
    );
    console.log(`更新完成,共修改${updateResult.modifiedCount}条文档`);
  } finally {
    await client.close();
  }
}

runUpdate().catch(console.dir);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:06:03