辅助节点上的MongoDB聚合框架

MongoDB aggregation framework on secondary node

本文关键字:框架 MongoDB 节点      更新时间:2023-10-16

如何使用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;

我需要在二级执行它。

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

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集群的辅助设备。