K2xL
K2xL

Reputation: 10320

MongoDB Aggregation Framework: Why do I have to use unwind? Why isn't there a $count?

I'm a bit confused on MongoDB's aggregation framework.

In order to do distinct counts of a specific field, I have to use the $addToSet operator, then $unwind, then $group with a $sum

What I'm not getting is why Mongo doesn't have a $count operator to just count the length of the array (instead of using $unwind and doing all the other steps)

What I'm doing now is just counting the length of the array in my driver, but technically my driver is having to download all the extra data.

Is there any reason why there isn't a $count or a $countUnique operator? Or is there some way to do this already with Mongo that I'm just not aware of?

Upvotes: 1

Views: 102

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

Upcoming 2.6 version adds a new operator $size which will give you the size of the array and can be used in $project stage after the $group with $addToSet to get the number you want.

References:

http://docs.mongodb.org/master/release-notes/2.6/#aggregation-enhancements http://docs.mongodb.org/master/reference/operator/aggregation/size/#exp._S_size

Upvotes: 1

Related Questions