tlikeit
tlikeit

Reputation: 105

Customized function in $group operator of aggregation framework in MongoDB

I want to use a customized $sum (lets call it $boolSum) function that returns the number of true element in an array. e.g.

group :{
          _id: {
                  a : '$a'
                  b : '$b',
                  c : '$c'
               },
              d1: { $boolSum : '$d1'}
              d2: { $boolSum : '$d2'}
        }

But it seems that there is no way to define boolSum function. I tried to add a new record in system.js, but it doesn't work.

In MongoDB, is it possible to cutomize function in $group operator of aggregation framework?

Upvotes: 1

Views: 97

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 52070

is it possible to cutomize function in $group operator of aggregation framework

No, not really...

I want to use a customized $sum (lets call it $boolSum) function that returns the number of true element in an array

... but you can combine $sum with other operators (like $cond in that particular case) to achieve the desired result:

{$sum: {$cond:["$someBooleanField",1,0]}}

or

{$sum: {$cond:[{$eq: ["$somePossiblyBooleanField",true]},1,0]}}

Upvotes: 3

Related Questions