1.mongodb有两个版本的C++驱动,一个是legacy,一个是要求编译器支持C++11的mongocxx。
2.安装c++ driver
本文是按照“Legacy Driver Documentation”教程来安装c++ driver的,地址是https://github.com/mongodb/mongo-cxx-driver/wiki/Download-and-Compile-the-Legacy-Driver
安装c++ driver前需要先安装boost(>=1.49)、python(2.x)、scons、git。
python(2.x)、scons、git都比较好安装,Ubuntu自带python,下面只讲一下boost的安装。
注意:安装编译boost前,得先安装gcc,使用命令:sudo apt-get install g++即可安装。
2.1.安装编译boost:
tar -zxvf boost_1_58_0.tar.gz
cd boost_1_58_0
编译前需要配置,输入下面的命令:
sudo ./bootstrap.sh
然后会提示你使用b2(老版本是使用bjam编译)编译,这里选择完全安装,自定义安装以后再研究,输入命令:
sudo ./b2 install
编译安装完成后,会把boost头文件拷贝到/usr/local/include/目录下,库文件在/usr/local/lib/下
2.2.安装编译c++ driver
获取源代码:
git clone https://github.com/mongodb/mongo-cxx-driver.git
选择分支:
cd mongo-cxx-driver
git checkout legacy
编译driver(SConstruct在mongo-cxx-driver文件夹里,需在mongo-cxx-driver目录下执行,否则提示没有SConstruct):
将driver安装在$HOME/mongo-client-install(也可以在/opt/local, /usr/local):
y@ubuntu:~/mongo-cxx-driver$ scons --prefix=$HOME/mongo-client-install install
启用ssl:
y@ubuntu:~/mongo-cxx-driver$ scons --prefix=$HOME/mongo-client-install --ssl install(没有成功,提示找不到boost,没在意,略过了)
启用sasl:
y@ubuntu:~/mongo-cxx-driver$ scons --prefix=$HOME/mongo-client-install --use-sasl-client install(没有成功,提示需要安装ssl,没在意,略过了)
建立driver的一个共享库版本:
scons --prefix=$HOME/mongo-client-install --sharedclient install
建立库的调试版本:
y@ubuntu:~/mongo-cxx-driver$ scons --prefix=$HOME/mongo-client-install --dbg=on --opt=on install
测试命令:g++ tutorial.cpp -pthread -lmongoclient -lboost_thread -lboost_system -lboost_regex -o tutorial
如果动态库没有加载进来,执行以下命令:
$ sudo echo "/usr/local/lib" >> /etc/ld.so.conf
$
sudo
ldconfig
安装过程的一些坑:
sudo scons -j2 --c++11=on --prefix=/usr/local --sharedclient install
编译成共享库,这里需要注意的是如果你的应用程序使用的是c++11记得也要打开c++11模式,否则在执行
mongo::client::initialize()
你将收获Program received signal SIGSEGV, Segmentation fault。
更多使用方法参考:https://mongodb.github.io/mongo-cxx-driver/