gpt4 book ai didi

c++ - MongoDb 求和聚合 C++

转载 作者:可可西里 更新时间:2023-11-01 10:04:06 25 4
gpt4 key购买 nike

我想将以下shell脚本(MongoDB shell版本:2.6.1)翻译成C++语言

db.account.aggregate([{$group: { _id:null, totalAmount: { $sum: "$amount" },count: { $sum: 1 }}}])

我尝试了以下代码:

     void test1(mongo::DBClientConnection& c)
{
BSONObj res;

BSONArray pipeline = BSON_ARRAY(
BSON( "$group" <<
BSON( "_id" << "null" ) <<
BSON( "totalAmount" << BSON( "$sum" << "$amount" ))<<
BSON( "count" << BSON( "$sum" << 1 ))
)
);

c.runCommand("test",BSON("aggregate" << "account" << "pipeline" << pipeline ),res);

cout << res.toString() << endl;
}

以上代码会导致编译错误!

     void test2(mongo::DBClientConnection& c)
{
BSONObj res;

vector<BSONObj> pipeline;
pipeline.push_back( BSON( "$group" << BSON( "_id" << "null" ) ) );
pipeline.push_back( BSON( "totalAmount" << BSON( "$sum" << "$amount" )) );

c.runCommand( "test", BSON( "aggregate" << "account" << "pipeline" << pipeline ), res);

cout << collection1<<res.toString() << endl;
}

以上代码会导致运行时错误!

谁能帮帮我?谢谢!

最佳答案

嗯..当我被执行时,这段代码运行成功。我有一张样张,但是“Stack overflow Answer”不允许我上传图片。:(

我想这是轻微的语法错误。你的sum加到组内了吗?检查你的代码。

以下是我的测试代码:

[代码]

DBClientConnection c;
BSONObj res;

vector<BSONObj> pipeline;
c.connect("127.0.0.1:27017");
pipeline.push_back( BSON( "$group" << BSON( "_id" << "null" << "totalAmount" << BSON( "$sum" << "$amount" ))));

c.runCommand( "security", BSON( "aggregate" << "nac" << "pipeline" << pipeline ), res);

cout << "Succeed!!!" << endl;
cout << "collection1: " << res.jsonString() << endl;

return 0;

[执行]

~/bin]$./test.exe

成功!!!

collection1: {result: [{_id: "null", totalAmount: 426 } ], ok: 1.0

~/bin]$

关于c++ - MongoDb 求和聚合 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com