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

MongoDB如何将嵌入文档数组中的值提取至根文档?

数据结构转换方案

原始数据示例

id: 119,
customfields: Array (2)
  0: Object
    value: "Mr"
    type: "salutation"
  1: Object
    value: "Google"
    type: "company"

目标输出示例

id: 119,
salutation: "Mr",
company: "Google"

重要说明:

  • 字段顺序无固定要求:部分记录中salutation可能在前,company可能在前,还可能包含其他无关字段,处理时直接忽略无关字段
  • 缺失字段不生成:若customfields数组中没有salutation或company记录,转换后不添加对应字段

处理逻辑示例(JavaScript)

function transformRecord(record) {
  const transformed = { id: record.id };
  // 遍历自定义字段数组,提取目标字段
  record.customfields?.forEach(item => {
    if (['salutation', 'company'].includes(item.type)) {
      transformed[item.type] = item.value;
    }
  });
  return transformed;
}

// 测试用例
const original = {
  id: 119,
  customfields: [
    { value: "Mr", type: "salutation" },
    { value: "Google", type: "company" }
  ]
};

console.log(transformRecord(original));
// 输出:{ id: 119, salutation: "Mr", company: "Google" }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:46:03