I’m trying to do something similar to
select column, count(*)
from table
group by column
in MongoDB.
I tried
db.table.group( {
key: 'column',
initial: {sum:0},
reduce: function(doc, prev) { prev.sum += 1; } }
})
I wanted to use something like $sum, but it was not working.
For
db.table.group( {
key: 'column'
} )
I’m getting
uncaught exception: group command failed: { "errmsg" : "$reduce has to be set", "ok" : 0 }
my mongoDB version is 2.0.8 (so I cannot use aggregation framework).
According to result I’m not getting the result for grouped column values, but result for
select count(*) from table
What am I doing wrong?
edit: (data added)
> db.table.find()
{ "_id" : ObjectId("50e180ce9449299428db83e8"), "column" : "a", "cnt" : 1 }
{ "_id" : ObjectId("50e180d09449299428db83e9"), "column" : "b", "cnt" : 2 }
{ "_id" : ObjectId("50e180d19449299428db83ea"), "column" : "c", "cnt" : 3 }
> db.table.group( { key: 'column', initial: { sum: 0}, reduce: function(doc, prev) { prev.sum += 1; } } )
[ { "sum" : 3 } ]
Maybe I’m using it in wrong way, but I expect
[ { "a": 1, "b": 1, "c": 1 } ]
The
keyshould be an object, not just a field name and you have an extra trailing}on thereduceline.Try this instead: