我正在尝试使用 mongo c++ 驱动程序创建一个客户端以连接到数据库。我成功地测试了本地主机的客户端。我使用的代码如下。
现在我想在不同的机器上拥有数据库和客户端,例如 IP 10.1.2.56 上的客户端和 IP 10.1.2.57 上的 mongodb
我应该在代码中进行更改以实现这一目标。我试图改变线路
c.connect("localhost"); //"192.168.58.1");
到
c.connect("10.1.2.57"); //"192.168.58.1");
但这不起作用错误说“caught can't connect to server 10.1.2.57:27017” 我试图 ping IP 10.1.2.57,它也给了我响应。
#include <iostream>
#include "mongo/client/dbclient.h"
// g++ src/mongo/client/examples/tutorial.cpp -pthread -Isrc -Isrc/mongo -lmongoclient -lboost_thread-mt -lboost_system -lboost_filesystem -L[path to libmongoclient.a] -o tutorial
//g++ tutorial.cpp -L[mongo directory] -L/opt/local/lib -lmongoclient -lboost_thread-mt -lboost_filesystem -lboost_system -I/opt/local/include -o tutorial
using namespace mongo;
void printIfAge(DBClientConnection& c, int age) {
auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", QUERY( "age" << age ).sort("name") );
while( cursor->more() ) {
BSONObj p = cursor->next();
cout << p.getStringField("name") << endl;
}
}
void run() {
DBClientConnection c;
c.connect("localhost"); //"192.168.58.1");
cout << "connected ok" << endl;
BSONObj p = BSON( "name" << "Joe" << "age" << 33 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Jane" << "age" << 40 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Abe" << "age" << 33 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Methuselah" << "age" << BSONNULL);
c.insert("tutorial.persons", p);
p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" );
c.insert("tutorial.persons", p);
c.ensureIndex("tutorial.persons", fromjson("{age:1}"));
cout << "count:" << c.count("tutorial.persons") << endl;
auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj());
while( cursor->more() ) {
cout << cursor->next().toString() << endl;
}
cout << "\nprintifage:\n";
printIfAge(c, 33);
}
int main() {
try {
run();
}
catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
return 0;
}