How mongodb aggregates statistics: calculate the combined value of B based on the type of field A (addition and subtraction)

problem description

has the following data structure:

{id:1, name: "apple", alias:"", price: 5, type: "add"}
{id:1, name: "apple", alias:"", price: 3, type: "minus"}
{id:1, name: "pear", alias:"", price: 6, type: "add"}
{id:1, name: "pear", alias:"", price: 3, type: "add"}
{id:1, name: "pear", alias:"", price: 1, type: "minus"}

the first piece of data is that you made 5 yuan (type is add), and the second item is 3 yuan (type is minus), etc.).
the result I want is

  1. classify according to name
  2. calculate the combined value of the final price based on the classification of 1

the combined value is determined according to the type of type. When type is add, price is added; when type is munus, price is subtracted

for example, the final expected result above is:

[
    {name: "apple", price: 2},    //5-3
    {name: "pear", price: 8}      //6+3-1
]

how to use aggregate statistics to calculate the final merge value of price? please ask the god to give us some advice. Thank you

Jul.07,2021

is a bit doubtful, why not just save it in the form {price: 5} , {price:-3} ? In this way, the calculation is much simpler, and people seem to understand it better.
to do the calculation in your current form, you need to write a more complex pipeline:

db.foo.aggregate([{
    $project: {
        name: 1,
        price: {
            $cond: {
                if: {$eq: ["$type", "minus"]},
                then: {$subtract: [0, "$price"]},
                else: "$price"
            }
        }
    }
}, {
    $group: {
        _id: "$name",
        price: {$sum: "$price"}
    }
}])

if you store it as I say:

db.foo.aggregate([{
    $group: {
        _id: "$name",
        price: {$sum: "$price"}
    }
}])
Is

much easier?

Menu