前言
mongocxx官网地址 http://mongocxx.org/?jmp=docs
本文的安装版本是:mongocxx-r3.3.1.tar.gz 。
参考文档安装过程 http://mongocxx.org/mongocxx-v3/installation/ 。
Linux系统信息:Linux
1.安装 MongoDB C driver.
如不安装它,直接装mongocxx cmake 时会报找不到libbson错误。
查看版本约束 :
For mongocxx-3.4.x, libmongoc 1.13.0 or later is required.
For mongocxx-3.3.x, libmongoc 1.10.1 or later is required.
For mongocxx-3.2.x, libmongoc 1.9.2 or later is required.
For mongocxx-3.1.4+, libmongoc 1.7.0 or later is required.
For mongocxx-3.1.[0-3], libmongoc 1.5.0 or later is required.
For mongocxx-3.0.x, we recommend the last 1.4.x version of libmongoc
下载及安装
$ git clone https://github.com/mongodb/mongo-c-driver.git
$ cd mongo-c-driver
$ git checkout 1.13.0 # To build a particular release
$ python build/calc_release_version.py > VERSION_CURRENT
$ mkdir cmake-build
$ cd cmake-build
$ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF ..
$ make -j4
$ sudo make install
cmake 这句一般会报错,像-- Could NOT find OpenSSL – SSL disabled 或者snappy未安装。
安装ssl:
sudo apt-get install openssl
sudo apt-get install libssl-dev
sudo apt install snappy
装好后接着make &&sudo make install
2.安装 MongoCXX
git clone https://github.com/mongodb/mongo-cxx-driver.git
cd mongo-cxx-driver
git checkout r3.3.1
mkdir cmake-build
cd cmake-build
cmake -DCMAKE_BUILD_TYPE=Release -DBSONCXX_POLY_USE_MNMLSTC=1 -DCMAKE_INSTALL_PREFIX=/usr/local ..
make EP_mnmlstc_core
make
sudo make install
3.安装mongodb
sudo apt install mongodb
要求3版本,不然会报版本不匹配。
4.测试
如下代码命名为 test.cpp
#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
int main(int, char**) {
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
bsoncxx::builder::stream::document document{};
auto collection = conn["testdb"]["testcollection"];
document << "hello" << "world";
collection.insert_one(document.view());
auto cursor = collection.find({});
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
}
c++ 编译
c++ --std=c++11 test.cpp -o test \
-I/usr/local/include/mongocxx/v_noabi \
-I/usr/local/include/bsoncxx/v_noabi \
-L/usr/local/lib -lmongocxx -lbsoncxx
c++ with pkg
要加环境变量 :
export PKG_CONFIG_PATH="/usr/lib/pkgconfig"
c++ --std=c++11 test.cpp -o test $(pkg-config --cflags --libs libmongocxx)
一切正常:输出
{ "_id" : { "$oid" : "5cde2da9507c320544455682" }, "hello" : "world" }
{ "_id" : { "$oid" : "5cde4ea2507c322c052060a2" }, "hello" : "world" }
如有问题,还是要多看官网与网友实践。