Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract from current field in mongodb with update using aggregation pipeline?

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

like image 568
uday214125 Avatar asked Feb 12 '18 06:02

uday214125


People also ask

How do I subtract in MongoDB?

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.

How do I subtract two dates in MongoDB?

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.

What is $$ root in MongoDB?

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.

What is $project in MongoDB?

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.


1 Answers

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.")
        }
});
like image 174
vijaykrishnavanshi Avatar answered Oct 21 '22 21:10

vijaykrishnavanshi