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

如何在MongoDB中基于品牌子文档修改店铺子文档的品牌引用?

MongoDB文档更新解决方案

可以通过聚合管道式更新实现需求,以下是具体的操作语句:

db.products.updateMany(
  {},
  [
    // 为brands数组的每个品牌添加id(按数组索引+1生成字符串id)
    {
      $set: {
        brands: {
          $map: {
            input: "$brands",
            as: "brand",
            in: {
              id: { $toString: { $add: [{ $indexOfArray: ["$brands.name", "$$brand.name"] }, 1] } },
              name: "$$brand.name"
            }
          }
        }
      }
    },
    // 将shops数组中各店铺的品牌名称替换为对应id
    {
      $set: {
        shops: {
          $map: {
            input: "$shops",
            as: "shop",
            in: {
              name: "$$shop.name",
              brands: {
                $map: {
                  input: "$$shop.brands",
                  as: "brandName",
                  in: {
                    $arrayElemAt: [
                      "$brands.id",
                      { $indexOfArray: ["$brands.name", "$$brandName"] }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    }
  ]
)

逻辑说明

  • 第一阶段:通过$map遍历顶层brands数组,利用$indexOfArray获取品牌的数组索引,加1后转为字符串作为id,同时保留原品牌名称。
  • 第二阶段:先遍历shops数组,对每个店铺再遍历其brands名称列表,通过$indexOfArray匹配顶层brands中的对应名称,再用$arrayElemAt取出对应的id完成替换。

可选调整

如果需要使用全局唯一标识符而非序列id,可将生成id的部分替换为{ $toString: { $objectId: "$$NOW" } },这样每个品牌会获得一个随机唯一的ObjectId字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:30:18