1

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?

1
  • Map/reduce and the aggregation framework work very differently. In the former, you can use all features of javascript and define your own methods. The latter relies on operators that are implemented internally in mongodb. However, M/R comes with a lot of overhead and, unlike the aggregation framework, wasn't really made for ad-hoc queries. Commented May 27, 2015 at 12:45

1 Answer 1

3

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]}} 
Sign up to request clarification or add additional context in comments.

2 Comments

It is similar to my current solution but seems to be better. Unlike your solution I used the $project operator which uses $cond to convert bool to int. I will try yours and see if it is faster than mine.
It is a suitable solution any way. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.