我想将以下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;
}
以上代码会导致运行时错误!
任何人都可以帮助我吗?谢谢!
答案 0 :(得分:3)
乌姆鲁.. 当我被执行时,此代码正在成功运行。 我有一个证明拍摄,但“Stack overflow Answer”不允许我上传图片。:(
我猜这是轻微的语法错误。您的金额是否添加到组内?检查你的代码。
以下是我的测试代码:
[代码]
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}
〜/二进制] $
答案 1 :(得分:0)
我不擅长英语,但我可以帮助你。
1)
void test1(mongo::DBClientConnection& c)
{
BSONObj res;
BSONArray pipeline = BSON_ARRAY(
BSONArray pipeline = BSON_ARRAY(
BSON( "$group" <<
BSON( "_id" << "null" << "totalAmount" << BSON( "$sum" << "$amount" ))<< "count" << BSON( "$sum" << 1 )
)
);
c.runCommand("test",BSON("aggregate" << "account" << "pipeline" << pipeline ),res);
cout << res.toString() << endl;
}
2)
void test2(mongo::DBClientConnection& c)
{
BSONObj res;
vector<BSONObj> pipeline;
pipeline.push_back( BSON( "$group" << BSON( "_id" << "null" << "totalAmount" << BSON( "$sum" << "$amount" ))));
c.runCommand( "test", BSON( "aggregate" << "account" << "pipeline" << pipeline ), res);
cout << collection1<<res.toString() << endl;
}