1、C++ driver download
地址:http://dl.mongodb.org/dl/cxx-driver/
這裡下載最新的cxx-driver/mongodb-linux-x86_64-v2.0-latest.tgz版本;
註:編譯驅動之前需要安裝pcre 和 scons 。並且g++版本需要4.0之後;
並且需要boost,關於boost的安裝可以參考前面一篇文章:http://blog.csdn.net/yuandianlws/article/details/7027538
2、 編譯
[root@cdh3-0005 mongo-cxx-driver-v2.0]# scons
編譯之後會出現libmongoclient.so
[root@cdh3-0005 mongo-cxx-driver-v2.0]# ls
authTest clientTest firstExample libmongoclient.a LICENSE.txt SConstruct whereExample
client config.log httpClientTest libmongoclient.so mongo secondExample
把 libmongoclient.so 拷貝至 /usr/local/lib下
[root@cdh3-0005 mongo-cxx-driver-v2.0]#cp libmongoclient.so /usr/local/lib
另外,由於目前mongo-cxx-driver沒有32位的driver包,所以你可以編譯MongoDB的原始碼進行安裝,裡麵包括了C++的driver
不過它需要下載依賴包
ftp://ftp.mozilla.org/pub/mozilla.org/js
cd src
make
make install
編譯mongoDB並install
tar -xvf mongodb-src-r2.0.4.tar.gz
cd mongodb-src-r2.0.4
scons --full install
3、測試
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace std;
using namespace mongo;
void run() {
DBClientConnection c;
c.connect("localhost"); //add port,c.connect("localhost:27017")
}
int main(void)
{
try {
run();
cout<<"connected ok"<<endl;
}catch(DBException& e){
cout<<"caught"<<e.what()<<endl;
}
return 0;
}
編譯:
[root@:~/svn/mongoDB]#g++ main.cpp -lmongoclient -lboost_thread -lboost_filesystem -lboost_program_options
運行:
[root@:~/svn/mongoDB]#./a.out
connected ok
另一個測試:
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace mongo;
int main() {
DBClientConnection conn;
BSONObj p = BSONObjBuilder().append("name", "Joe").append("age", 33).obj();
try {
conn.connect("localhost");
cout << "connected ok" << endl;
} catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
conn.insert("tutorial.persons", p);
conn.insert("tutorial.persons", p);
conn.insert("tutorial.persons", p);
return 0;
}
g++ -o mongo_insert mongo_insert.cpp -lmongoclient -lboost_thread -lboost_filesystem -lboost_program_options
$ ./insert mongoconnected ok
運行mongo用戶端驗證插入:
$ cd ~/usr/mongo/bin
$ ./mongo
MongoDB shell version: 1.8.2
connecting to: test
> show dbs
admin (empty)
local (empty)
tutorial 0.0625GB
> use tutorial
switched to db tutorial
> db.persons.find()
{ "_id" : ObjectId("4e11a582b918b66ebf3835fb"), "name" : "Joe", "age" : 33 }
{ "_id" : ObjectId("4e11a582b918b66ebf3835fc"), "name" : "Joe", "age" : 33 }
{ "_id" : ObjectId("4e11a582b918b66ebf3835fd"), "name" : "Joe", "age" : 33 }
>
OK,這樣使用和開發都可以了。
參考:MongoDB C++開發環境搭建 http://www.cnblogs.com/logicbaby/archive/2011/07/04/2097697.html