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:
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' } }