Absolute value with MongoDB aggregation structure

I use the MongoDB aggregation structure and should take the absolute value of the sum field, which I use both in the project part and in the group part, for example:

'$project' => { 'amount' => 1, '_id' => 0 } 

....

  '$group' => { 'total' => {'$sum' => '$amount'} } 

How do you take the absolute value of the "sum" field in this case? I could not find it in the documents (maybe it is not available?)

+8
mongodb aggregation-framework
source share
1 answer

It is not directly accessible, but you can do this using the $cond and $subtract statements inside the $project , like this (as a JavaScript object):

 { $project: { amount: { $cond: [ { $lt: ['$amount', 0] }, { $subtract: [0, '$amount'] }, '$amount' ] }}} 

So, if amount < 0 , then 0 - amount , otherwise amount used directly.

UPDATE

As with the 3.2 release of MongoDB, you can use the new expression operator of the expression $abs . it is straight:

 { $project: { amount: { $abs: '$amount' } } 
+12
source share

All Articles