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.
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" ]}
}
}
])
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" ]}
}
}
])
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