如何通过同一文档中的另一个字段 $inc 一个字段?

How to $inc a field by another field in the same document?

如何使用 $inc 中另一个字段的值来定义增加多少?

示例-

一些文档

{_id: obi, length: 256, delta: 6}

在这里,我想以 delta 增量增加长度。

伪代码为

db.collection.update({}, $inc: {length: $delta});

感谢您的帮助...

简单的更新操作不允许在其他字段中使用内部字段,无论是任何运算符,

对于解决方案,您可以使用 update with aggregation pipeline 从 MongoDB 4.2 开始,

  • 使用 $add/$sum 两者中的任何运算符对两个字段求和
db.collection.update({},
  [{
    $set: {
      length: {
        $add: ["$length", "$delta"]
      }
    }
  }]
)

Playground