如何在Node.js中合并MongoDB两个集合的查询结果(无需新建集合)
MongoDB 平级合并两个集合的最优方法
我有如下两个MongoDB集合:
// Collection1 { id: 01, name: "John", year: 2022 }, { id: 02, name: "Smith", year: 2022 } // Collection2 { id: 03, name: "Mathias", year: 2022 }, { id: 04, name: "Carl", year: 2022 }
希望无需新建集合,得到如下平级合并的结果:
// 输出结果 { id: 01, name: "John", year: 2022 }, { id: 02, name: "Smith", year: 2022 }, { id: 03, name: "Mathias", year: 2022 }, { id: 04, name: "Carl", year: 2022 }
尝试过使用$lookup,但结果总是子数组,想要类似SQL中UNION的平级数组效果,求最优实现方法。
最优解决方案:使用$unionWith(MongoDB 4.4+)
$unionWith是MongoDB专门为集合平级合并设计的聚合操作,语法简洁且性能最优,直接返回两个集合的平级文档列表:
db.collection1.aggregate([ { $unionWith: { coll: "collection2" } } ])
- 默认行为:自动去重(如果两个集合存在
_id相同的文档,只会保留一份) - 若需保留所有文档(包括重复),可指定空管道实现类似SQL的UNION ALL效果:
db.collection1.aggregate([ { $unionWith: { coll: "collection2", pipeline: [{}] } } ])
兼容旧版本方案:$facet + $concatArrays
如果你的MongoDB版本低于4.4,可以用聚合管道的$facet和$concatArrays组合实现:
db.collection1.aggregate([ // 分别获取两个集合的文档数据 { $facet: { coll1Docs: [{ $match: {} }], coll2Docs: [{ $lookup: { from: "collection2", pipeline: [], as: "docs" } }] } }, // 合并两个集合的数组 { $project: { merged: { $concatArrays: ["$coll1Docs", { $arrayElemAt: ["$coll2Docs.docs", 0] }] } } }, // 展开合并后的数组 { $unwind: "$merged" }, // 将子文档提升为顶层文档 { $replaceRoot: { newRoot: "$merged" } } ])
内容的提问来源于stack exchange,提问作者Louisdrake
相关产品推荐
相关产品推荐

