I'm using the MongoDB aggregation framework and need to take the absolute value of an amount field, which I use in both the project portion and the group portion, ex:
'$project' => {
'amount' => 1,
'_id' => 0
}
....
'$group' => {
'total' => {'$sum' => '$amount'}
}
How do you take the absolute value of the 'amount' field in this case? I wasn't able to find it in the docs (maybe it's not available?)
It's not directly available, but you can do it using a $cond
operator and a $subtract
within a $project
like this (as a JavaScript object):
{ $project: {
amount: {
$cond: [
{ $lt: ['$amount', 0] },
{ $subtract: [0, '$amount'] },
'$amount'
]
}}}
So if amount < 0
, then 0 - amount
is used, otherwise amount
is used directly.
UPDATE
As of the 3.2 release of MongoDB, you can use the new $abs
aggregation expression operator to do this directly:
{ $project: { amount: { $abs: '$amount' } }
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