我在使 mongodb 的 $group 命令在 C++ (Qt) 中工作时遇到问题
文档的示例代码按预期工作并返回结果:
db.article.aggregate(
{ "$group" : {
"_id" : "$author",
"docsPerAuthor" : { "$sum" : 1 }
}}
);`
不过,转换为 C++ 会返回一个空结果集,但不会出现错误:
QString queryCommand = "{ group : {"
"_id : \"$author\", "
"docsPerAuthor : {$sum : 1} "
"}}";
BSONObj bson_query_result = m_mongoConnection.findOne("data.collection",
fromjson(queryCommand.toStdString().c_str()));
std::cout << "Output: " << bson_query_result.toString() << std::endl;
最佳答案
聚合是通过“runCommand”方法调用的,该方法采用数据库名称和包含命令和集合的 BSONObj,加上作为数组的实际管道。最后一个参数是响应对象。满documentation .
假设您有一个 DBClientConnection m_mongoConnection 并使用“测试”数据库:
BSONObj res;
BSONArray pipeline = BSON_ARRAY(
BSON( "$group" <<
BSON( "_id" << "$author" ) <<
BSON( "docsPerAuthor" <<
BSON( "$sum" << 1 )
)
)
);
m_mongoConnection.runCommand(
"test", BSON(
"aggregate" << "article" << "pipeline" << pipeline
),
res
);
cout << res.toString() << endl
取决于您对如何构造 BSON 参数的个人喜好。
关于c++ - C++ 中的 MongoDB $group 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22691103/