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
相关产品推荐
相关产品推荐

