如何使用聚合管道从mongodb中的当前字段中减去更新?

uda*_*125 4 mongoose mongodb mongodb-query aggregation-framework

基本上我想从总数中减去该值并通过减去值更新它。

db.invoice.update({ "_id": ObjectId(req.params.id) },
    { "$set": { "total": total - 200 } }, function (err, doc) {
        if (err) return new Error(err);
        if (doc.result.n > 0) {
            console.log(" Invoice updated with Payment info.", doc.result);
        } else {
            console.log("Something went wrong while payment info updation.")
        }
});
Run Code Online (Sandbox Code Playgroud)

我不知道如何在这里实现这一目标。我找到了用于与当前字段相乘的 $mul 运算符,但我没有在 mongodb 中找到 $sub 运算符。我找到了 $subtract 聚合,但我无法将 $subtract 与 update() 一起使用。

有人可以帮助我吗?请

谢谢

vij*_*shi 13

您可以将 $inc 运算符与负值一起使用。

db.invoice.update({ "_id": ObjectId(req.params.id) },
    { "$inc": { "total": -200 } }, function (err, doc) {
        if (err) return new Error(err);
        if (doc.result.n > 0) {
            console.log(" Invoice updated with Payment info.", doc.result);
        } else {
            console.log("Something went wrong while payment info updation.")
        }
});
Run Code Online (Sandbox Code Playgroud)