如何使用MongoDB聚合将源集合数组添加到匹配legacyId的目标集合
MongoDB跨集合关联新增points字段实现方案
1. 仅查询合并结果(不修改原集合)
直接通过$lookup关联两个集合,调整字段输出即可,聚合语句如下:
db.targetCollection.aggregate([ // 按legacyId字段关联sourceCollection { $lookup: { from: "sourceCollection", localField: "legacyId", foreignField: "legacyId", as: "sourceTemp" } }, // 拆分关联得到的数组(因单legacyId对应单条source记录,拆分后为单个对象) { $unwind: "$sourceTemp" }, // 提取points为顶层字段,保留targetCollection原有字段 { $project: { _id: 1, legacyId: 1, name: 1, type: 1, points: "$sourceTemp.points" } } ])
如果需要保留未匹配到source的target文档,可将$unwind部分修改为:
{ $unwind: { path: "$sourceTemp", preserveNullAndEmptyArrays: true } }
2. 直接更新targetCollection原有文档
如果需要把points字段永久写入targetCollection,可在聚合末尾加$merge阶段将结果写回原集合(MongoDB 4.2及以上版本支持):
db.targetCollection.aggregate([ { $lookup: { from: "sourceCollection", localField: "legacyId", foreignField: "legacyId", as: "sourceTemp" } }, { $unwind: { path: "$sourceTemp", preserveNullAndEmptyArrays: true } }, // 新增points字段,未匹配到的文档默认赋值空数组 { $addFields: { points: { $ifNull: ["$sourceTemp.points", []] } } }, // 删除临时关联字段 { $unset: "sourceTemp" }, // 按_id匹配更新原集合文档 { $merge: { into: "targetCollection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } } ])
运行后targetCollection的文档将新增对应points字段,示例结果如下:
{ "_id": ObjectId("xxx"), "legacyId": 2, "name": "Name 2", "type": "Area", "points": [ {"latitude": "lat value 2", "longitude": "long value 2"}, {"latitude": "lat value 3", "longitude": "long value 3"}, {"latitude": "lat value 4", "longitude": "long value 4"} ] }
内容的提问来源于stack exchange,提问作者wheeliea
相关产品推荐
相关产品推荐

