使用MongoDB updateOne将valueArray首对象value设为comments尾值
解决MongoDB数组字段更新问题
问题分析
你原来的更新语句无法生效,因为普通的$set更新不允许直接引用当前文档内的其他字段值(比如$comments.value这类聚合表达式),必须使用MongoDB 4.2及以上版本支持的聚合管道式更新才能实现需求。
正确的updateOne语句
db.collection.updateOne( { "_id": 1 }, [ { "$set": { "valueArray.0.value": { "$cond": { "if": { "$eq": [{ "$size": "$comments" }, 0] }, "then": "", "else": { "$arrayElemAt": ["$comments.value", -1] } } } } } ] )
代码说明
- 将更新参数设为聚合数组形式,这样就能使用聚合表达式引用文档内部字段
- 通过
$cond判断comments数组长度:- 若数组为空,把
valueArray.0.value设为空字符串 - 若数组非空,用
$arrayElemAt提取comments.value数组的最后一个元素(索引-1)
- 若数组为空,把
$comments.value会自动把comments数组中每个对象的value字段提取为新数组,再取其末尾元素
执行结果
执行上述语句后,目标文档的valueArray[0].value会被更新为comments数组最后一个元素的value值(即"from"),与你期望的输出一致:
[ { "_id": 1, "comments": [ { "value": "hello" }, { "value": "world" }, { "value": "from" } ], "status": false, "user": "abc", "valueArray": [ { "isValid": true, "value": "from" }, { "isValid": false, "value": 75 }, { "isValid": false, "value": 12 } ] } ]
内容的提问来源于stack exchange,提问作者vadapav
相关产品推荐
相关产品推荐

