[转]MongoDB c++驱动安装与使用

  1. 安装
    • 获取源码:git clone https://github.com/mongodb/mongo-cxx-driver.git,解压
    • 安装编译工具scons:yum install -y scons
    • 编译:进入mongo-cxx-driver目录,执行:scons --prefix=/home/work/mongo/ --sharedclient install
    • 驱动已被安装在/home/work/mongo中
  2. 使用
    • 编译示例程序
      #include <cstdlib>
      #include <iostream>
      #include "mongo/client/dbclient.h" // for the driver
      
      void run() {
        mongo::DBClientConnection c;
        c.connect("localhost");
      }
      
      int main() {
          mongo::client::initialize();
          try {
              run();
              std::cout << "connected ok" << std::endl;
          } catch( const mongo::DBException &e ) {
              std::cout << "caught " << e.what() << std::endl;
          }
          return EXIT_SUCCESS;
      }
    • gcc tutorial.cpp -I./mongo/include -L./lib/ -L./mongo/lib -lmongoclient -Wl,-rpath=./lib/ -o tutorial
    • 上面的编译选项中,mongo、lib与tutorial.cpp位于同一目录,mongo即是第一步中指定的安装目录,lib存放其他依赖库,如boost。

  更多文章,请关注零一积流

原文地址:https://www.cnblogs.com/rd-log/p/4810327.html