I have a data. Let me show you the example of that
1
1
2
2
2
3
And, I’d like to get the number of each values using Group by. The result will be like below
value | count
1 | 2
2 | 3
3 | 1
Maybe, the group by query on Mongo Shell is like this
db.collection.group(
{ key : {value:true},
reduce: function(obj, prev) { prev.csum += 1; },
initial: { csum: 0 }
})
But, I have to convert that query to C code with mongoDB C API.
I tried to make some code using bson_append_bson like that.. but, failed..
What shoould I do?
I setup a Mongo 2.2.1 instance on my machine on port 12345. I created a
test.datacollection and populated it withper your sample data. Using the latest driver, I wrote the following sample code.
Instead of the
$groupcommand, which doesn’t work in sharded environments, I used the Aggregation Framework (new since 2.1). The above C code is the equivalent toin the Mongo shell.