You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:06:03