如何按entry_id为MongoDB 2021年后文档批量添加entrant_company字段
解决MongoDB批量按entry_id添加entrant_company字段的问题
针对你描述的场景——2021年后的文档缺失entrant_company字段,该字段值对应同entry_id下credit_role为"Advertising Agency"的credit_name,可以通过聚合管道结合批量更新实现需求,替代你当前只能单条更新的代码:
批量更新代码
db.entries.updateMany( // 匹配2021年之后的所有文档 { year: { $gt: 2021 } }, [ // 关联同集合,获取当前entry_id下的广告代理信息 { $lookup: { from: "entries", localField: "entry_id", foreignField: "entry_id", pipeline: [ { $match: { credit_role: "Advertising Agency", year: { $gt: 2021 } } } ], as: "agency_info" } }, // 从关联结果中提取广告代理名称作为entrant_company { $set: { entrant_company: { $arrayElemAt: ["$agency_info.credit_name", 0] } } }, // 清理临时生成的agency_info字段 { $unset: "agency_info" } ] )
代码说明
- $lookup阶段:在同一个集合内,根据
entry_id匹配到对应分组中角色为"Advertising Agency"的文档,将结果存入临时数组agency_info。 - $set阶段:通过
$arrayElemAt从agency_info数组中取出第一个元素的credit_name(假设每个entry_id仅对应一个广告代理文档),赋值给entrant_company。 - $unset阶段:移除临时字段,保持文档结构整洁。
验证更新结果(可选)
执行更新前,可以先通过聚合查询验证结果是否符合预期:
db.entries.aggregate([ { $match: { year: { $gt: 2021 } } }, { $lookup: { from: "entries", localField: "entry_id", foreignField: "entry_id", pipeline: [ { $match: { credit_role: "Advertising Agency", year: { $gt: 2021 } } } ], as: "agency_info" } }, { $addFields: { entrant_company: { $arrayElemAt: ["$agency_info.credit_name", 0] } } }, { $unset: "agency_info" }, { $limit: 10 } // 查看前10条数据验证 ])
内容的提问来源于stack exchange,提问作者dave
相关产品推荐
相关产品推荐

