如何在MongoDB中将重复current_product_id对应的related_product_id合并为数组
MongoDB按current_product_id去重合并关联ID的解决方案
原代码失效的核心原因
- 聚合操作默认是查询操作,没有配置写入阶段的情况下不会修改原有集合的数据,所以你执行后原库数据没有变化
- 核心逻辑错误:分组的主键错设为
related_product_id[0],完全不符合你按current_product_id去重的需求 - 多余的
$unwind、$match阶段逻辑完全不匹配当前需求,$match中的字段引用写法也不符合MongoDB语法规范
正确实现代码
场景1:生成新的去重集合(推荐,不破坏原数据)
执行后结果会写入testing1_deduplicated新集合,校验数据无误后可替换原集合:
db.testing1.aggregate([ // 按current_product_id分组,汇总所有对应的related_product_id { $group: { _id: "$current_product_id", // 若需要related_product_id自身也去重,把$push替换为$addToSet即可 related_product_id: { $push: "$related_product_id" } } }, // 调整字段格式,和原有结构对齐 { $project: { _id: 0, current_product_id: "$_id", related_product_id: 1 } }, // 结果写入新集合 { $out: "testing1_deduplicated" } ])
场景2:直接修改原集合(确认逻辑无误后使用)
把最后一步的$out替换为$merge即可直接覆盖原集合的去重数据:
{ $merge: { into: "testing1", on: "current_product_id", whenMatched: "replace", whenNotMatched: "insert" } }
内容的提问来源于stack exchange,提问作者coder87
相关产品推荐
相关产品推荐

