[英]How to connect two Client IP to the same mongodb using c++ Drivers
我正在嘗試使一個具有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");
但這不起作用該錯誤提示“捕獲到無法連接到服務器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;
}
我找到了上述問題的答案
早些時候mongod在Mongodb服務器端的已定義端口和路徑上運行
所以我通過以下命令停止了Mongodb
$ sudo stop mongodb
然后通過以下命令使用默認定義的路徑再次啟動服務器
$ sudo mongod --dbpath /data/db --port 27017
然后在c ++中嘗試了上述代碼,這次將其連接到遠程服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.