Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute value with MongoDB aggregation framework

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?)

like image 939
Mellop Avatar asked Jul 10 '13 03:07

Mellop


1 Answers

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' } }
like image 167
JohnnyHK Avatar answered Sep 22 '22 05:09

JohnnyHK