MongoDB如何批量更新_id存在于另一集合中的所有文档
方法1:Mongo Shell命令行实现(优先方案)
无需额外脚本,直接通过MongoDB自带的命令行工具即可完成操作:
- 若使用交互式Mongo Shell,连接到对应数据库后执行以下命令:
// 提取所有待更新的文档ID const targetIds = db.docIdsToUpdate.distinct("docId"); // 批量更新匹配的文档 db.docs.updateMany( { _id: { $in: targetIds } }, { $set: { deleted: true } } );
执行后会返回更新结果,modifiedCount字段即为实际修改的文档数量。
- 若需要直接在系统终端执行无需进入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实现,可参考以下代码:
- 先安装MongoDB Node.js驱动:
npm install mongodb
- 编写执行脚本:
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
相关产品推荐
相关产品推荐

