MongoDB使用$inc+$set更新文档报错,求最优解决方案
问题解决方法
你的报错根源是在聚合管道的$cond条件中,错误地用字符串字面量"tryCount"引用字段,而没有使用MongoDB聚合管道的字段引用语法$tryCount。以下是修正后的语句:
db.getCollection("errors").updateOne( { _id: ObjectId("63ff2a2351c56c92e265cf4c") }, [ { $inc: { tryCount: 1 } }, { $set: { status: { $cond: { if: { $gte: ["$tryCount", 4] }, then: "failed", else: "$status" } } } } ] );
关键修改点:
- 将条件中的
"tryCount"改为"$tryCount",确保聚合管道能正确引用$inc后更新的字段值 - 用
updateOne替代update,更贴合单文档更新的场景(update在MongoDB 4.2+虽支持管道,但updateOne语义更明确)
逻辑说明:
- 先通过
$inc将tryCount自增1 - 用
$cond判断自增后的tryCount是否大于等于4(即原数值大于3),满足则将status设为failed,否则保留原status值
内容的提问来源于stack exchange,提问作者Fırat Taşkın
相关产品推荐
相关产品推荐

