Reputation: 663
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.
Upvotes: 4
Views: 7713
Reputation: 93
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" ]}
}
}
])
Upvotes: 8
Reputation: 2029
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" ]}
}
}
])
Upvotes: 6