Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于C API的mongodb分组_Mongodb_Group By_Database - Fatal编程技术网

基于C API的mongodb分组

基于C API的mongodb分组,mongodb,group-by,database,Mongodb,Group By,Database,我有一份数据。让我给你举个例子 一, 1. 2. 2. 2. 三, 我想用GROUPBY得到每个值的数目。结果如下所示 值|计数 1 | 2 2 | 3 3 | 1 也许,Mongo Shell上的分组查询是这样的 db.collection.group( { key : {value:true}, reduce: function(obj, prev) { prev.csum += 1; }, initial: { csum: 0 } }) 但是,我必须使用mongoDB

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

一, 1. 2. 2. 2. 三,

我想用GROUPBY得到每个值的数目。结果如下所示

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

也许,Mongo Shell上的分组查询是这样的

db.collection.group(
{ key : {value:true},
reduce: function(obj, prev) { prev.csum += 1; },
initial: { csum: 0 }
})
但是,我必须使用mongoDB C API将该查询转换为C代码。 我试着像那样使用bson\u append\u bson来编写一些代码。。但是,失败了


我该怎么办?

我在我的机器上的端口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 );
}
在蒙戈贝壳里

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