2

我有一个数据。让我给你看一个例子

1 1 2 2 2 3

而且,我想使用 Group by 获取每个值的数量。结果将如下所示

价值 | 计数 1 | 2 2 | 3 3 | 1

也许,Mongo Shell 上的 group by query 是这样的

db.collection.group(
{ key : {value:true},
reduce: function(obj, prev) { prev.csum += 1; },
initial: { csum: 0 }
})

但是,我必须使用 mongoDB C API 将该查询转换为 C 代码。我试图像那样使用 bson_append_bson 编写一些代码..但是,失败了..

我该怎么办?

4

1 回答 1

0

我在我的机器上的端口 12345 上设置了一个 Mongo 2.2.1 实例。我创建了一个test.data集合并填充了它

use test
db.data.insert({value:1})
db.data.insert({value:1})
db.data.insert({value:2})
db.data.insert({value:2})
db.data.insert({value:2})
db.data.insert({value:3})

根据您的样本数据。使用最新的驱动程序,我编写了以下示例代码。

#include <stdio.h>
#include <mongo.h>

int main( char *argv[] ) {
    bson b, out;
    mongo conn;

    if( mongo_connect( &conn, "127.0.0.1", 12345 ) != MONGO_OK ) {
        switch( conn.err ) {
            case MONGO_CONN_NO_SOCKET:
                printf( "FAIL: Could not create a socket!\n" );
                break;
            case MONGO_CONN_FAIL:
                printf( "FAIL: Could not connect to mongod. Make sure it's listening at 127.0.0.1:27017.\n" );
                break;
            }

        exit( 1 );
    }

    bson_init( &b );
        bson_append_string( &b, "aggregate", "data" );
        bson_append_start_array( &b, "pipeline" );
            bson_append_start_object( &b, "0" );
                bson_append_start_object( &b, "$group" );
                    bson_append_string( &b, "_id", "$value" );
                    bson_append_start_object( &b, "count" );
                        bson_append_int( &b, "$sum", 1 );
                    bson_append_finish_object( &b );
                bson_append_finish_object( &b );
            bson_append_finish_object( &b );
        bson_append_finish_array( &b );
    bson_finish( &b );
    bson_print( &b );

    printf( "command result code: %d\n", mongo_run_command( &conn, "test", &b, &out ) );
    bson_print( &out );

    bson_destroy( &b );
    bson_destroy( &out );
    mongo_destroy( &conn );
    return( 0 );
}

$group不是在分片环境中不起作用的命令,我使用了聚合框架(自 2.1 以来的新功能)。上面的C代码等价于

use test
db.data.aggregate({$group:{_id:"$value",count:{$sum:1}}})

在 Mongo 外壳中。

于 2012-11-22T18:18:07.567 回答