MongoDB $group command in c++

MongoDB $group command in c++

本文关键字:in c++ command group MongoDB      更新时间:2023-10-16

我有问题得到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,以及实际的管道(数组)。最后一个参数是响应对象。全部文档。

假设您有一个DBClientConnection m_mongoConnection并使用"test"数据库:

 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参数取决于您的个人品味。