前言
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" }
如有問題,還是要多看官網與網友實踐。