我正在尝试使用mongo c ++驱动程序创建一个客户端来连接数据库。我成功测试了localhost的客户端。我用的代码如下。
现在我想在不同的机器上安装数据库和客户端,例如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");
但这不起作用 错误说“捕获无法连接到服务器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;
}
答案 0 :(得分:0)
我找到了上述问题的答案
之前,mongod正在Mongodb服务器端定义的端口和路径上运行
所以我按照命令
停止了Mongodb$ sudo stop mongodb
并再次使用以下命令
启动具有默认定义路径的服务器$ sudo mongod --dbpath /data/db --port 27017
然后在c ++中尝试了上面的代码,这次它连接到远程服务器。