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 に答える