Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo subtract in group aggregation

I have a mongo query and I need to group and than subtract min value from max value and I have issues doing that.

Here is my query:

{
    $group : {
        _id :  {
            type: "$type",
            id : "$id"
            },
        sent : {$subtract: [{$max : "$value"}, {$min : "$value"}]}
    }
}

But I get this error message:

The $subtract accumulator is a unary operator

I would like to know how do I subtract inside the group stage.

like image 200
František Jeřábek Avatar asked Sep 11 '25 07:09

František Jeřábek


2 Answers

An alternative to Yathish Manjunath's answer is to use $addFields operator:

db.[collection].aggregate([   
    {
        $group : {
            _id :  {
                type: "$type",
                id : "$id"
            }, 
            maxValue : {$max : "$value"} , 
            minValue : {$min : "$value"}
        }
    },
    {
        $addFields : {
            sent : {$subtract: [ "$maxValue", "$minValue" ]}
        }
    }
]) 
like image 96
Guilherme Xavier Avatar answered Sep 13 '25 21:09

Guilherme Xavier


Can you try the below query :

db.[collection].aggregate([   
{
        $group : {
            _id :  {
                type: "$type",
                id : "$id"
                }, 
            maxValue : {$max : "$value"} , 
            minValue : {$min : "$value"}
        }
    },
    {
        $group : {
            _id :  {
                type: "$_id.type",
                id : "$_id.id"
                }, 
            sent : {$subtract: [ "$maxValue", "$minValue" ]}
        }
    }
 ]) 
like image 44
Yathish Manjunath Avatar answered Sep 13 '25 22:09

Yathish Manjunath