MongoDB聚合操作:如何将字符串数组转为对象数组并拆分assets字段
MongoDB聚合实现assets数组字符串转自定义键对象
原数据结构
[ { "_id": ObjectId("5c949609ff5e3d6119758730"), "assets": [ "one##two##three##four", "one##two##hello##world" ] } ]
期望转换结果
[ { "_id": ObjectId("5c949609ff5e3d6119758730"), "assets": [ { "firstkey": "one", "secondkey": "two", "thirdkey": "three", "fourthkey": "four" }, { "firstkey": "one", "secondkey": "two", "thirdkey": "hello", "fourthkey": "world" } ] } ]
聚合查询实现方法
方法一:直接构造自定义键对象
通过$map遍历assets数组,对每个字符串用$split拆分后,用$arrayElemAt取出对应位置的值并赋值给自定义键:
db.collection.aggregate([ { $addFields: { assets: { $map: { input: "$assets", as: "item", in: { $let: { vars: { parts: { $split: ["$$item", "##"] } }, in: { firstkey: { $arrayElemAt: ["$$parts", 0] }, secondkey: { $arrayElemAt: ["$$parts", 1] }, thirdkey: { $arrayElemAt: ["$$parts", 2] }, fourthkey: { $arrayElemAt: ["$$parts", 3] } } } } } } } } ])
方法二:用$zip+$arrayToObject动态生成对象
如果自定义键名数量较多,这种方式更简洁:将键名数组和拆分后的字符串数组合并,再转成对象:
db.collection.aggregate([ { $addFields: { assets: { $map: { input: "$assets", as: "item", in: { $arrayToObject: { $zip: { inputs: [["firstkey", "secondkey", "thirdkey", "fourthkey"], { $split: ["$$item", "##"] }] } } } } } } } ])
说明
两种方法都能在聚合查询中直接定义firstkey、secondkey等自定义键名,完成从字符串到目标对象的转换。
内容的提问来源于stack exchange,提问作者xxestter
相关产品推荐
相关产品推荐

