MongoDB聚合:根据字段是否存在执行条件$lookup查询
MongoDB聚合查询:按需关联集合保留或补充history字段
我有两个集合collection1和collection2,数据结构如下:
// collection1 数据
[ { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] }, { "_id": 101, "text": "i am naughty"} ]
// collection2 数据
[ { "_id": 1, "collection1Id":100, "date":"2023-6-1", "updated":"2023-6-2" }, { "_id": 2, "collection1Id":101, "date":"2023-7-3", "updated":"2023-7-5" } ]
需求是:对collection1执行聚合查询,当文档不存在history字段时,关联collection2获取对应数据作为history;如果已经存在history字段,则直接保留原字段内容。预期输出如下:
[ { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] }, { "_id": 101, "text": "i am naughty", "history":[{"_id": 2, "collection1Id": 101, "date":"2023-7-3", "updated":"2023-7-5"}] } ]
解决方案
通过$lookup结合条件判断可以实现该需求,具体聚合查询代码如下:
db.collection1.aggregate([ // 关联collection2,将匹配数据存入临时字段 { $lookup: { from: "collection2", localField: "_id", foreignField: "collection1Id", as: "matchedHistory" } }, // 按条件替换或保留history字段 { $addFields: { history: { $cond: { if: { $exists: ["$history", true] }, then: "$history", else: "$matchedHistory" } } } }, // 清理临时字段 { $project: { matchedHistory: 0 } } ])
步骤说明
- $lookup阶段:将
collection1的_id与collection2的collection1Id做关联,把匹配到的结果存入临时字段matchedHistory。 - $addFields阶段:用
$cond配合$exists判断文档是否存在history字段:- 存在则直接保留原
history数据; - 不存在则用
matchedHistory的值填充history字段。
- 存在则直接保留原
- $project阶段:移除临时字段
matchedHistory,让输出结构更简洁。
执行以上聚合查询后,就能得到符合预期的结果。
内容的提问来源于stack exchange,提问作者MuhammadWaseem
相关产品推荐
相关产品推荐

