Reputation: 583
Basically I want to subtract the value from total and update it by subtracted value.
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.")
}
});
I don't know how to achieve this here. I found $mul operator for multiplication with current field but I didn't find $sub operator in mongodb. I found $subtract aggregation but I am unable to use $subtract with update().
Could someone help me? Please
Thanks
Upvotes: 9
Views: 12770
Reputation: 813
You can use $inc operator with the negative value.
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.")
}
});
Upvotes: 21