Explore Courses Blog Tutorials Interview Questions
0 votes
in Web Technology by (47.6k points)

I am playing around with MongoDB trying to figure out how to do a simple

SELECT province, COUNT(*) FROM contest GROUP BY province

But I can't seem to figure it out using the aggregate function. I can do it using some really weird group syntax{ 

"key": { 

"province": true 


"initial": { 

"count": 0 


"reduce": function(obj, prev) { 

if (true != null) if (true instanceof Array) prev.count += true.length; 

else prev.count++; 


But is there an easier/faster way using the aggregate function?

2 Answers

0 votes
by (106k points)

In MongoDB group by can be used by using below-mentioned code:-


{"$group" : {_id:"$province", count:{$sum:1}}} 


0 votes
by (108k points)

If you need multiple columns to group by, follow the following model:


    "$group": {

        _id: {

            status: "$status",

            type: "$type"


        count: {

            $sum: 1




Related questions

0 votes
1 answer
asked Jul 10, 2019 in BI by Vaibhav Ameta (17.6k points)
+3 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories