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

Posted

技术标签:

【中文标题】如何使用聚合管道从 mongodb 中的当前字段中减去更新?【英文标题】:How to subtract from current field in mongodb with update using aggregation pipeline? 【发布时间】:2018-07-22 06:50:53 【问题描述】:

基本上我想从总计中减去该值并通过减去的值对其进行更新。

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.")
        
);

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

有人可以帮我吗?请

谢谢

【问题讨论】:

【参考方案1】:

您可以使用带有负值的 $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.")
        
);

【讨论】:

谢谢它的工作,但我不能在更新中使用聚合吗? 你可以,但这是最简单的方法。

以上是关于如何使用聚合管道从 mongodb 中的当前字段中减去更新?的主要内容,如果未能解决你的问题,请参考以下文章

在 MongoDB 的聚合管道中获取 $group 之后的输入文档中的字段

为啥在与数组中的字段匹配时,mongoDB聚合中的查找中的管道不起作用?

如何使用 MongoDB 聚合管道从集合中的两个子文档中返回最小值?

Mongodb 聚合管道限制 $lookup 字段

MongoDB——聚合管道之$project操作

MongoDB——聚合管道之$project操作