2014-03-27 43 views
0

我得到的MongoDB的$組命令在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; 

回答

2

聚合是通過「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參數。

+1

你好,謝謝你的建議,這是非常有用的,但我覺得你的代碼中有一個小錯誤:哪裏是BSONArray管道= BSON_ARRAY( BSON(「$組」 << BSON(「_id」 < BSON(「$ sum」<< 1) ) ) );(「$ author」)<< (「docsPerAuthor」<< ) BSON(「$ sum」<< 1) ) )應該是BSONArray pipeline = BSON_ARRAY(「$ group」<< )BSON(「_id」<<「$ author」<<「docsPerAuthor」<< ) ); – Pih