本文介绍如何在 mongodb 中通过 update + 聚合管道(update with aggregation pipeline)对“数组中的对象数组”执行精准 upsert 操作:当指定 category 和 item 存在时,向其 sub_list 追加新值;若 item 不存在则自动添加新对象;若整个文档不存在则创建新文档。
本文介绍如何在 mongodb 中通过 update + 聚合管道(update with aggregation pipeline)对“数组中的对象数组”执行精准 upsert 操作:当指定 category 和 item 存在时,向其 sub_list 追加新值;若 item 不存在则自动添加新对象;若整个文档不存在则创建新文档。
在 MongoDB 4.2+ 中,db.collection.update() 支持以聚合管道作为更新操作符,这使得处理复杂嵌套结构(如数组内含对象、对象内含数组)成为可能。传统 $push 或 $set 无法同时满足「按子字段定位 + 条件追加 + 不存在则创建」三重要求,而聚合管道更新可完美解决。
const categoryVal = "A";const itemToFind = 1;const valToAdd = 68;db.collection.update( { "category": categoryVal }, [ { $set: { list: { $cond: { if: { $in: [ itemToFind, { $ifNull: ["$list.item", []] } ] }, then: { $map: { input: "$list", in: { $cond: { if: { $and: [ { $eq: ["$$this.item", itemToFind] }, { $not: { $in: [valToAdd, { $ifNull: ["$$this.sub_list", []] }] } } ] }, then: { $mergeObjects: [ "$$this", { sub_list: { $concatArrays: [ { $ifNull: ["$$this.sub_list", []] }, [valToAdd] ] } } ] }, else: "$$this" } } } }, else: { $concatArrays: [ [ { item: itemToFind, sub_list: [valToAdd] } ], { $ifNull: ["$list", []] } ] } } } } } ], { upsert: true });
该方案是 MongoDB 处理深层嵌套 upsert 场景的推荐实践,兼顾表达力、健壮性与性能,适用于商品 SKU 管理、用户标签系统、配置项动态维护等典型业务场景。