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

MongoDB如何从info数组k键提取信息并更新数组对象

MongoDB实现info数组字段拆分更新方案

核心逻辑是通过聚合算子拆分k字段的下划线分隔值,映射为A、B、C三个字段后合并到原数组元素中,同时保留你原有过滤掉v为"-"的逻辑。

场景1:查询时返回预期结构(不修改原文档)

使用聚合查询实现,代码如下:

db.你的集合名.aggregate([
  {
    $addFields: {
      info: {
        $map: {
          // 先执行原有过滤逻辑
          input: {
            $filter: {
              input: "$info",
              as: "p",
              cond: { $ne: ["$$p.v", "-"] }
            }
          },
          as: "item",
          in: {
            // 合并原有字段和新增的A/B/C字段
            $mergeObjects: [
              "$$item",
              {
                A: {
                  $convert: {
                    input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 0] },
                    to: "int",
                    onError: "NA"
                  }
                },
                B: {
                  $convert: {
                    input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 1] },
                    to: "int",
                    onError: "NA"
                  }
                },
                C: {
                  $convert: {
                    input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 2] },
                    to: "int",
                    onError: "NA"
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

场景2:永久更新集合中的文档(MongoDB 4.2及以上版本支持)

使用带聚合管道的update操作实现,代码如下:

db.你的集合名.updateMany(
  // 可自定义匹配需要更新的文档条件,这里默认匹配所有有info字段的文档
  { info: { $exists: true } },
  [
    {
      $set: {
        info: {
          $map: {
            input: {
              $filter: {
                input: "$info",
                as: "p",
                cond: { $ne: ["$$p.v", "-"] }
              }
            },
            as: "item",
            in: {
              $mergeObjects: [
                "$$item",
                {
                  A: { $convert: { input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 0] }, to: "int", onError: "NA" } },
                  B: { $convert: { input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 1] }, to: "int", onError: "NA" } },
                  C: { $convert: { input: { $arrayElemAt: [{ $split: ["$$item.k", "_"] }, 2] }, to: "int", onError: "NA" } }
                }
              ]
            }
          }
        }
      }
    }
  ]
)

逻辑说明

  • $split:将k字段的字符串按下划线切割为数组,例如"2_3_4"会被切割为["2","3","4"]
  • $arrayElemAt:按索引提取切割后数组的对应值,索引从0开始,对应A取第0位、B取第1位、C取第2位
  • $convert:将提取到的字符串转为数字类型,若对应索引无值、转换失败时返回预设的"NA"
  • $mergeObjects:将原数组元素的k、v字段和新增的A、B、C字段合并,生成新的数组元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:18:03