MongoDB数组对象更新:存在则增量,不存在则新增
MongoDB数组元素的更新或新增实现
示例文档
{ "_id" : "1", "principal" : "Joe", "classroom" : [ { "grade" : "1", "class" : "A", "totalStudent" : 10.0 }, { "grade" : "1", "class" : "B", "totalStudent" : 20.0 } ] }
需求
- 当筛选条件匹配时,递增
totalStudent字段,例如筛选条件为principal : "Joe", classroom.grade: "1", classroom.class: "A" - 当目标对象不存在时,向
classroom数组中新增对象,例如新增classroom.grade: "1", classroom.class: "C"对应的对象
现有查询(仅支持存在对象的增量操作)
db.getCollection("classsroom").updateOne( { pricipal: "Joe", "classroom": {$elemMatch: {"grade":"1","class": "A"}} }, { $inc: { "classroom.$.totalStudent": 5 } }, {upsert: true} )
解决方案
要同时实现匹配元素递增、不匹配则新增的需求,使用聚合管道更新语法即可一步完成:
db.getCollection("classroom").updateOne( { principal: "Joe" }, [ { $set: { classroom: { $cond: { if: { $ne: [ { $filter: { input: "$classroom", cond: { $and: [{ $eq: ["$$this.grade", "1"] }, { $eq: ["$$this.class", "C"] }] } } }, [] ] }, then: { $map: { input: "$classroom", in: { $cond: { if: { $and: [{ $eq: ["$$this.grade", "1"] }, { $eq: ["$$this.class", "C"] }] }, then: { $mergeObjects: ["$$this", { totalStudent: { $add: ["$$this.totalStudent", 5] } }] }, else: "$$this" } } } }, else: { $concatArrays: [ "$classroom", [{ grade: "1", class: "C", totalStudent: 5 }] ] } } } } } ], { upsert: true } )
逻辑说明
- 外层条件
{ principal: "Joe" }定位目标文档 - 通过
$filter判断数组中是否存在指定grade和class的元素 - 若存在,用
$map遍历数组,对匹配元素执行totalStudent递增操作,其他元素保持原样 - 若不存在,用
$concatArrays向数组末尾新增包含初始值的目标对象
期望执行结果
{ "_id" : "1", "principal" : "Joe", "classroom" : [ { "grade" : "1", "class" : "A", "totalStudent" : 10.0 }, { "grade" : "1", "class" : "B", "totalStudent" : 20.0 }, { "grade" : "1", "class" : "C", "totalStudent" : 5.0 } ] }
内容的提问来源于stack exchange,提问作者Rungkrit Titachotnimit
相关产品推荐
相关产品推荐

