MongoDB使用aggregate关联三个集合获取指定嵌套格式结果问题
问题核心错误
你的聚合查询中两个$lookup关联阶段的localField和foreignField字段设置完全颠倒,同时最终$project阶段的字段映射不符合预期输出结构。
修复后的聚合查询
db.t_user_credentials.aggregate([ { $lookup: { from: "t_credentials", // 用当前用户凭证表存储的凭证外键关联凭证表的主键 localField: "credential_id", foreignField: "_id", as: "credential" } }, { $unwind: { path: "$credential", preserveNullAndEmptyArrays: true } }, { $lookup: { from: "t_groups", // 用当前用户凭证表存储的分组外键关联分组表的主键 localField: "group_id", foreignField: "_id", as: "group" } }, { $unwind: { path: "$group", preserveNullAndEmptyArrays: true } }, { $project: { first_name: "$identifiers.first_name", middle_name: "$identifiers.middle_name", last_name: "$identifiers.last_name", credential: 1, group: 1, created_at: 1 } } ])
上述查询执行后输出结果完全匹配你给出的预期格式。
内容的提问来源于stack exchange,提问作者Kode Kamper
相关产品推荐
相关产品推荐

