安装
c++ 驱动 依赖 c驱动
先装c驱动
mongo-c-driverhttps://github.com/mongodb/mongo-c-driverhttps://github.com/mongodb/mongo-c-driver
wget https://github.com/mongodb/mongo-c-driver/releases/download/1.19.0/mongo-c-driver-1.19.0.tar.gz
tar xzf mongo-c-driver-1.19.0.tar.gz
cd mongo-c-driver-1.19.0
mkdir cmake-build
cd cmake-build
cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF ..
sudo cmake --build . --target install
再装c++的
wget https://github.com/mongodb/mongo-cxx-driver/releases/download/r3.6.5/mongo-cxx-driver-r3.6.5.tar.gz
tar xzf mongo-cxx-driver-r3.6.5.tar.gz
mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local
make && make install
sudo ldconfig
简单示例
// g++ -o test --std=c++11 main.cc -I/usr/local/include/mongocxx/v_noabi -I/usr/local/include/libmongoc-1.0 -I/usr/local/include/bsoncxx/v_noabi -I/usr/local/include/libbson-1.0 -L/usr/local/lib -lmongocxx -lbsoncxx
#include <stdio.h>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/string/to_string.hpp>
#include <iostream>
using namespace std;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
int main()
{
// 初始化
mongocxx::instance instance{};
// 链接
mongocxx::uri uri("mongodb://username:password@192.168.4.20:27017/devices");
mongocxx::client client(uri);
// 选择数据库和集合
mongocxx::database db = client["devices"];
mongocxx::collection coll = db["device_types"];
mongocxx::options::find opts{};
// opts.projection(make_document(kvp("schema", 0), kvp("_id", 0)));
opts.projection(document{} << "_id" << 0 << "schema" << 0 << finalize);
const char *filter = "{\"owner\" : \"pressure_117\"}";
auto cursor = coll.find(bsoncxx::from_json(filter), opts);
// 循环查找
for(auto&& doc : cursor)
{
cout << bsoncxx::to_json(doc) << endl;
}
return 0;
}
简单cmake
cmake_minimum_required(VERSION 3.2 FATAL_ERROR)
project(mongo LANGUAGES CXX)
set(SYS_LIBS )
list(APPEND SYS_LIBS -lmongocxx -lbsoncxx)
include_directories(/usr/local/include/bsoncxx/v_noabi)
include_directories(/usr/local/include/mongocxx/v_noabi)
add_executable(main
main.cc
)
target_link_libraries(main
${SYS_LIBS}
)
附录
官网示例https://github.com/mongodb/mongo-cxx-driver/blob/master/exampleshttps://github.com/mongodb/mongo-cxx-driver/blob/master/examplesapi 文档http://mongocxx.org/api/current/classmongocxx_1_1database.html
http://mongocxx.org/api/current/classmongocxx_1_1database.html