初次接触MongoDB C++开发,发现官方单独提供的C++ Driver源码包似乎有些问题,经一番折腾后方才顺利的能跑,故在此记下第一篇。
我使用的开发环境Slackware 13.37 x86,既然官方单独提供的C++ Driver有些问题那就全部MongoDB源码构建出.a库吧,首先从(http://downloads.mongodb.org/src/mongodb-src-r1.8.2.tar.gz)处下载MongoDB的源码包,编译后包括了MongoDB本身和C++ Driver库。
安装前的准备:
把mongodb安装在$HOME/usr/mongo:
$ mkdir -p ~/usr/mongo
$ tar xvf mongodb-src-r1.8.2.tar.gz
$ scons --prefix=$HOME/usr/mongo --full install
执行完后查看$HOME/usr/mongo下三个目录bin、include、lib。
启动mongodb:
$ mkdir -p ~/usr/mo_data
$ cd ~/usr/mongo/bin
$ ./mongo --dbpath=$HOME/usr/mo_data
写个简单的小程序测试下生成的libmongoclient.a。
#include < iostream >
#include " client/dbclient.h "
using namespace mongo;
void run() {
DBClientConnection c;
c.connect( " localhost " );
}
int main() {
try {
run();
cout << " connected ok " << endl;
} catch ( DBException & e ) {
cout << " caught " << e.what() << endl;
}
return 0 ;
}
$ g++ mon2.cpp -I ~/usr/mongo/include/mongo/ ~/usr/mongo/lib/libmongoclient.a -lboost_thread -lboost_filesystem -lboost_program_options
$ ./a.out
connected ok
第二个程序执行简单的插入。
#include < iostream >
#include " 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++ mon3.cpp -I ~/usr/mongo/include/mongo/ ~/usr/mongo/lib/libmongoclient.a -lboost_thread -lboost_filesystem -lboost_program_options
$ ./a.out
connected 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,这样使用和开发都可以了。