MongoDB使用aggregation $lookup关联集合并输出指定格式结果
MongoDB $lookup 关联查询实现方案
以下是针对USER_CREDENTIAL和CREDENTIAL集合关联、输出指定结构的完整聚合查询语句:
db.USER_CREDENTIAL.aggregate([ // 关联CREDENTIAL集合获取对应title数据 { $lookup: { from: "CREDENTIAL", localField: "credential_id", foreignField: "_id", as: "credential_info" } }, // 拆分lookup返回的数组,转为对象格式(单条credential_id仅匹配一条关联数据) { $unwind: "$credential_info" }, // 按照要求格式化输出字段结构 { $project: { _id: 0, user_credential_id: "$_id", member: { first_name: "$identifier.first_name", middle_name: "$identifier.middle_name", last_name: "$identifier.last_name", title: "$credential_info.title", created_at: "$created_at" } } } ])
补充说明
- 如果存在credential_id无效、关联不到对应CREDENTIAL数据的场景,可以给
$unwind添加preserveNullAndEmptyArrays: true参数,避免关联失败的数据被直接过滤,此时title字段会返回null - 不需要保留无效关联数据时,使用默认$unwind配置即可
内容的提问来源于stack exchange,提问作者Kode Kamper
相关产品推荐
相关产品推荐

