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 }]] } ] } } } ] )
代码解释
- 查询条件:通过
$in选中目标用户,逻辑与原始查询一致。 - 聚合管道更新:
$set:重新赋值booksBought数组$cond:核心条件判断,先检查数组中是否包含"harry potter":- 存在时:用
$map遍历数组,对匹配到的书籍执行$add(等价于$inc)操作,其余元素保持原样 - 不存在时:用
$concatArrays将原数组与新的书籍对象合并,实现添加效果
- 存在时:用
验证结果
执行上述更新后,两个用户的文档会符合预期:
- Josh的"harry potter"数量从1变为11
- Carl的
booksBought数组新增"harry potter"条目,数量为10
内容的提问来源于stack exchange,提问作者user874737
相关产品推荐
相关产品推荐

