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

MongoDB多文档:匹配元素时更新数组,不匹配时添加元素

解决MongoDB批量更新数组:存在则递增,不存在则添加的问题

问题背景

需要批量更新指定用户(userId为10000001和10000002)的booksBought数组:

  • 若用户已拥有booktitle为"harry potter"的书籍,将其quantity递增10
  • 若用户未拥有该书籍,将{"booktitle": "harry potter", "quantity": 10}添加到数组中

原始查询仅能处理已有目标书籍的用户,无法为无该书籍的用户添加新元素。

解决方案:使用聚合管道式更新

MongoDB 4.2及以上版本支持在updateMany/update中使用聚合管道,通过条件判断实现需求逻辑:

db.collection.updateMany(
  { "userId": { $in: ["10000001", "10000002"] } },
  [
    {
      $set: {
        booksBought: {
          $cond: [
            // 判断数组中是否存在harry potter
            { $in: ["harry potter", "$booksBought.booktitle"] },
            // 存在则遍历数组,匹配到的元素递增quantity,其余保持不变
            {
              $map: {
                input: "$booksBought",
                as: "item",
                in: {
                  $cond: [
                    { $eq: ["$$item.booktitle", "harry potter"] },
                    { booktitle: "$$item.booktitle", quantity: { $add: ["$$item.quantity", 10] } },
                    "$$item"
                  ]
                }
              }
            },
            // 不存在则拼接原数组和新书籍对象
            { $concatArrays: ["$booksBought", [{ booktitle: "harry potter", quantity: 10 }]] }
          ]
        }
      }
    }
  ]
)

代码解释

  1. 查询条件:通过$in选中目标用户,逻辑与原始查询一致。
  2. 聚合管道更新:
    • $set:重新赋值booksBought数组
    • $cond:核心条件判断,先检查数组中是否包含"harry potter":
      • 存在时:用$map遍历数组,对匹配到的书籍执行$add(等价于$inc)操作,其余元素保持原样
      • 不存在时:用$concatArrays将原数组与新的书籍对象合并,实现添加效果

验证结果

执行上述更新后,两个用户的文档会符合预期:

  • Josh的"harry potter"数量从1变为11
  • Carl的booksBought数组新增"harry potter"条目,数量为10

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:46:15