1

如何使用 C++ 驱动在辅助节点上执行聚合框架任务?

这是一个始终在主节点上执行的示例:

DBClientConnection c;
bo res;

vector<bo> pipeline;
pipeline.push_back( BSON( "$match" << BSON( "firstName" << "Stephen" ) ) );

c.connect( "localhost:12345" );
c.runCommand( "test", BSON( "aggregate" << "people" << "pipeline" << pipeline ), res );

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

我需要在二级上执行它。

4

1 回答 1

0

虽然我没有使用过 MongoDB 的 C++ 驱动程序,但只需将读取首选项设置为辅助,就可以轻松地在辅助上运行聚合。例如在外壳上:

mongo -u admin -p <pwd> --authenticationDatabase admin --host 
RS-repl0-0/server-1.servers.example.com:27017,server-2.servers.example.com:27017
RS-repl0-0:PRIMARY> use test
switched to db test
RS-repl0-0:PRIMARY> db.setSlaveOk() // Ok to run commands on a slave
RS-repl0-0:PRIMARY> db.getMongo().setReadPref('secondary') // Set read pref
RS-repl0-0:PRIMARY> db.getMongo().getReadPrefMode()
secondary
RS-repl0-0:PRIMARY> db.zips.aggregate( [
...    { $group: { _id: "$state", totalPop: { $sum: "$pop" } } },
...    { $match: { totalPop: { $gte: 10*1000*1000 } } }
... ] )
{ "_id" : "CA", "totalPop" : 29754890 }
{ "_id" : "FL", "totalPop" : 12686644 }
...

可以从 MongoDB 日志中验证这确实在辅助节点上运行:

...
2016-12-05T06:20:14.783+0000 I COMMAND  [conn200] command test.zips command: aggregate { aggregate: "zips", pipeline: [ { $group: { _id: "$state", totalPop: { $sum: "$pop" } } }, { 
$match: { totalPop: { $gte: 10000000.0 } } } ], cursor: {} } keyUpdates:0 writeConflicts:0 numYields:229 reslen:338 locks:{ Global: { acquireCount: { r: 466 } }, Database: { acquire
Count: { r: 233 } }, Collection: { acquireCount: { r: 233 } } } protocol:op_command 49ms
...

请注意,这也适用于分片 MongoDB 集群的辅助节点。

于 2016-12-13T04:50:25.500 回答