MongoDB如何将文档多个字段值合并为新数组字段并过滤无效值
解决方案
错误原因
普通更新语法不支持在操作符中直接解析文档字段引用,你写的$monthlyProd1会被直接识别为普通字符串存入数组,无法读取对应字段的实际值。MongoDB 4.2及以上版本支持聚合管道形式的更新操作,可以实现字段读取、过滤等逻辑,你的运行环境为MongoDB 4.4.9,完全支持该特性。
通用实现方案(无需手动罗列所有月度字段)
该方案会自动匹配所有monthlyProd开头的字段,自动过滤空字符串,仅保留Object类型的有效值,不需要手动逐个写月度字段名:
db.monthlyProdData.updateMany({}, [ { $set: { monthlyProd: { $filter: { input: { $objectToArray: "$$ROOT" }, cond: { $and: [ // 匹配字段名符合monthlyProd加数字的规则 { $regexMatch: { input: "$$this.k", regex: /^monthlyProd\d+$/ } }, // 过滤空字符串值 { $ne: [ "$$this.v", "" ] }, // 仅保留Object类型的值 { $eq: [ { $type: "$$this.v" }, "object" ] } ] } } } } }, // 提取过滤结果中的实际值,丢弃字段名信息 { $set: { monthlyProd: "$monthlyProd.v" } } ] )
固定字段版本(月度字段数量固定可使用)
如果你确认月度字段只有固定的几个,只想手动指定要提取的字段,可以用下面的写法:
db.monthlyProdData.updateMany({}, [ { $set: { monthlyProd: { $filter: { input: [ "$monthlyProd1", "$monthlyProd2", "$monthlyProd3" ], cond: { $and: [ { $ne: [ "$$this", "" ] }, { $eq: [ { $type: "$$this" }, "object" ] } ] } } } } } ] )
前置测试建议
执行更新前建议先通过find测试逻辑是否符合预期,避免误改数据:
db.monthlyProdData.find({}, { name: 1, testMonthlyProd: { $filter: { input: { $objectToArray: "$$ROOT" }, cond: { $and: [ { $regexMatch: { input: "$$this.k", regex: /^monthlyProd\d+$/ } }, { $ne: [ "$$this.v", "" ] }, { $eq: [ { $type: "$$this.v" }, "object" ] } ] } } } }).limit(10)
内容的提问来源于stack exchange,提问作者amota
相关产品推荐
相关产品推荐

