关于c driver取得执行结果的问题

heartlesstoanyone heartlesstoanyone 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我现在有一个需求,求表中一字段的累加之和,表结构及mapreduce执行结果如下:
shard1:PRIMARY> db.mytest.find()
{ "_id" : 1, "name" : "apple", "price" : 10 }
{ "_id" : 2, "name" : "boy", "price" : 5 }
{ "_id" : 3, "name" : "apple", "price" : 20 }
{ "_id" : 4, "name" : "apple", "price" : 30 }
{ "_id" : 5, "name" : "cup", "price" : 10 }
{ "_id" : 6, "name" : "cup", "price" : 20 }
{ "_id" : 7, "name" : "dark", "price" : 10 }
{ "_id" : 8, "name" : "dark", "price" : 10 }
{ "_id" : 9, "name" : "egg", "price" : 10 }
{ "_id" : 0, "name" : "film", "price" : 10 }
shard1:PRIMARY> db.runCommand({ mapreduce:'mytest', map:function() { emit(1,{sum:this.price}); }, reduce:function(key, values) { var a = values[0]; for (var i=1;i < values.length; i++) { var b = values[i]; a.sum += b.sum; } return a; }, out:{inline:1}})
{
"results" : [
{
"_id" : 1,
"value" : {
"sum" : 135
}
}
],
"timeMillis" : 1,
"counts" : {
"input" : 10,
"emit" : 10,
"reduce" : 1,
"output" : 1
},
"ok" : 1
}

我现在需要在c代码中取到sum的值,该如何做?
如下是无法取到sum值的:
bson cmd;
bson out = {NULL, 0};
bson_init(&cmd);
bson_append_string(&cmd, "mapreduce", "mytest");
bson_append_string(&cmd, "map", "function(){ emit(1,{sum:this.a_price}); }");
bson_append_string(&cmd, "reduce", "function(key, values){ var a = values[0]; for (var i=1;i < values.length; i++) { var b = values[i]; a.sum += b.sum; } return a; }");
bson_append_string(&cmd, "out", "{outline:1}");
bson_finish(&cmd);
const int result = mongo_run_command(conn, "mydb", &cmd, &out);
bson_print((const bson *)&out);

bson_print的结果是:
result : 2 {outline:1}
timeMillis : 16 56
counts : 3
input : 16 6
emit : 16 6
reduce : 16 1
output : 16 1

ok : 1 1.000000
...全文
评论 1
收藏 已收藏
分享
返回顶部
heartlesstoanyone
MongoDB 1,797 成员 1,466 内容