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

MongoDB聚合管道问题:合并用户邮箱与手机号至单文档

修正Mongoose聚合管道:合并用户联系方式并格式化手机号

问题分析

当前聚合管道在$group阶段使用$first获取email和phone时,无法正确区分不同类型的联系方式,导致手机号被错误赋值为邮箱,同时缺少手机号格式化逻辑。

修正后的聚合管道

[
  {
    $lookup: {
      from: "usercontactinfos",
      localField: "_id",
      foreignField: "REF_UserID",
      as: "uci"
    }
  },
  {
    $unwind: {
      path: "$uci",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $lookup: {
      from: "contactinfos",
      localField: "uci.REF_ContactInfoID",
      foreignField: "_id",
      as: "ci"
    }
  },
  {
    $unwind: {
      path: "$ci",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      _id: 1,
      fName: 1,
      lName: 1,
      email: {
        $cond: {
          if: { $eq: ["$ci.type", 0] },
          then: "$ci.value",
          else: null
        }
      },
      phoneRaw: {
        $cond: {
          if: { $eq: ["$ci.type", 1] },
          then: "$ci.value",
          else: null
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      fName: { $first: "$fName" },
      lName: { $first: "$lName" },
      email: { $max: "$email" },
      phoneRaw: { $max: "$phoneRaw" }
    }
  },
  {
    $project: {
      _id: 1,
      fName: 1,
      lName: 1,
      email: 1,
      phone: {
        $regexReplace: {
          input: "$phoneRaw",
          regex: /^(\d{3})(\d{3})(\d{4})$/,
          replacement: "$1-$2-$3"
        }
      }
    }
  }
]

修正说明

  1. 修复联系方式赋值错误
    原$group阶段的$first会固定取分组后第一个文档的值,导致非目标类型的字段被错误赋值。改用$max:MongoDB中字符串优先级高于null,$max会自动筛选出每个用户对应的非null邮箱和手机号。

  2. 添加手机号格式化
    新增最后一个$project阶段,使用$regexReplace将10位纯数字手机号格式化为xxx-xxx-xxxx的标准格式,正则表达式捕获数字的三段分组并通过连字符拼接。

验证结果

执行修正后的管道后,将返回期望的结果:

{
  "_id": "65d7e9a82bd4a4e423570962",
  "fName": "Mike",
  "lName": "Liss",
  "email": "michael.liss@live.com",
  "phone": "510-207-1234"
}

内容的提问来源于stack exchange,提问作者MrLister

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:15:20