0

我正在尝试做类似的事情

select column, count(*) 
  from table
 group by column

在 MongoDB 中。

我试过了

db.table.group( {
    key: 'column',
    initial: {sum:0},
    reduce: function(doc, prev) { prev.sum += 1; } }
})

我想使用 $sum 之类的东西,但它不起作用。

为了

db.table.group( {
    key: 'column'
} )

我越来越

uncaught exception: group command failed: { "errmsg" : "$reduce has to be set", "ok" : 0 }

我的 mongoDB 版本是 2.0.8(所以我不能使用聚合框架)。

根据结果​​,我没有得到分组列值的结果,而是得到

select count(*) from table

我究竟做错了什么?

编辑:(添加数据)

> 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 } ]

也许我以错误的方式使用它,但我希望

[ { "a": 1, "b": 1, "c": 1 } ]
4

1 回答 1

1

应该是一个对象,而key不仅仅是一个字段名称,并且您}在该reduce行上有一个额外的尾随。

试试这个:

db.table.group({
    key: {column: 1},
    initial: {sum:0},
    reduce: function(doc, prev) { prev.sum += 1; }
})
于 2012-12-31T14:14:17.087 回答