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
MongoDB provides a variety of arithmetic expression operators. The $subtract operator is one of those operators. This operator is used to subtract two numbers or dates and returns the difference.
In MongoDB, you can use the $subtract aggregation pipeline operator to subtract numbers and/or dates. Specifically, $subtract can do the following three things: Subtract two numbers to return the difference. Subtract a number (in milliseconds) from a date and return the resulting date.
The $$ROOT variable contains the source documents for the group. If you'd like to just pass them through unmodified, you can do this by $pushing $$ROOT into the output from the group.
Definition. $project. Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.
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.")
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With