一、安装:
官方安装教程:http://mongocxx.org/mongocxx-v3/installation/
note: The mongocxx driver builds on top of the MongoDB C driver.
#mongoc
git clone https://github.com/mongodb/mongo-c-driver.git
cd mongo-c-driver/build/
cmake ..
make
sudo make install
#mongocxx
git clone https://github.com/mongodb/mongo-cxx-driver.git
cd mongo-cxx-driver/build/
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local -DBSONCXX_POLY_USE_MNMLSTC=1 -DLIBBSON_DIR=/usr/lib ..
sudo cmake --build . --target EP_mnmlstc_core
make
sudo make install
验证是否安装成功过
main.cc
#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;
}
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(mongocxx_test)
set(CMAKE_CXX_STANDARD 17)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
#mongocxx
find_package(mongocxx REQUIRED)
include_directories(${LIBMONGOCXX_INCLUDE_DIR})
#bsoncxx
find_package(bsoncxx REQUIRED)
include_directories(${LIBBSONCXX_INCLUDE_DIR})
#exe
add_executable(test main.cc)
target_link_libraries(test
mongo::bsoncxx_shared
mongo::mongocxx_shared
)
输出
{ "_id" : { "$oid" : "5fd75eab96e17f538b114d92" }, "hello" : "world" }
二、基本用法(增、删、查、改)
#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
// 如果使用到auto关键字且不做参数类型检查(或将代码放到try中)可以大幅简化代码
int main(int, char**) {
// 建立连接
mongocxx::instance instance{}; // This should be done only once.
mongocxx::client client{mongocxx::uri{}};
// 上面代码等同于:
// mongocxx::instance instance{}; // This should be done only once.
// mongocxx::uri uri("mongodb://localhost:27017");
// mongocxx::client client(uri);
// 访问数据库(Database)
mongocxx::database database = client["test_datebase"];
// mongocxx::database database = client[uri.database()];
// 访问集合(Collection)
mongocxx::collection collection = database["test_collection"];
// auto collection = client["test_datebase"]["test_collection"];
// 删除之前的记录
database.drop();
// --------------------------------------------------------------
// 创建一个json文档(Document)
// {
// "name" : "MongoDB",
// "type" : "database",
// "count" : 1,
// "versions": [ "v1.0", "v2.0", "v3.0" ],
// "info" : {
// "x" : 1314,
// "y" : 520
// }
// }
auto builder = bsoncxx::builder::stream::document{};
bsoncxx::document::value doc_value = builder
<< "name" << "MongoDB"
<< "type" << "database"
<< "count" << 1
<< "versions" << bsoncxx::builder::stream::open_array
<< "v1.0" << "v2.0" << "v3.0"
<< close_array
<< "info" << bsoncxx::builder::stream::open_document
<< "x" << 1314
<< "y" << 520
<< bsoncxx::builder::stream::close_document
<< bsoncxx::builder::stream::finalize;
bsoncxx::document::view view = doc_value.view();
// --------------------------------------------------------------
// 访问 JSON 文档 string 字段
bsoncxx::document::element element = view["name"];
if(element.type() != bsoncxx::type::k_string) {
std::cout << "name type error." << std::endl;
}
std::string name = element.get_string().value.to_string();
std::cout << "name: " << name << std::endl;
// 访问 JSON 文档 array 字段
element = view["versions"];
if (element.type() != bsoncxx::type::k_array) {
std::cout << "versions type error." << std::endl;
}
bsoncxx::array::view version = element.get_array().value; // 获取到的元素为 array view
std::cout << "version:" << std::endl;
for (bsoncxx::array::element var : version) {
std::string value = var.get_string().value.to_string();
std::cout << " " << value;
}
std::cout << std::endl;
// 访问 JSON 文档 document 字段
element = view["info"];
if (element.type() != bsoncxx::type::k_document) {
std::cout << "info type error." << std::endl;
}
bsoncxx::document::view info = element.get_document().value; // 获取到的元素依然为 document view
std::cout << "info:" << std::endl;
bsoncxx::document::element ele1 = info["x"];
if (ele1.type() != bsoncxx::type::k_int32) {
std::cout << "ele1 type error" << std::endl;
}
int x = ele1.get_int32().value;
std::cout << " x: " << x << std::endl;
int y = info["y"].get_int32().value; // 如果不做参数类型检查,可以使用这种简单的方式
std::cout << " y: " << y << std::endl;
// --------------------------------------------------------------
// 插入单个文档
bsoncxx::stdx::optional<mongocxx::result::insert_one> insert_one_result = collection.insert_one(doc_value.view());
bsoncxx::oid oid = insert_one_result->inserted_id().get_oid().value;
std::string insert_id = oid.to_string();
std::cout << "\nInsert one document, return id is " << insert_id << std::endl;
// 如果你没有在文档中手动指定 _id 字段,MongoDB 会自动的在插入的文档中添加一个 _id字段。
// 插入多个文档
std::vector<bsoncxx::document::value> documents;
for(int i = 0; i < 10; i++) {
documents.push_back(bsoncxx::builder::stream::document{} << "i" << i << finalize);
}
bsoncxx::stdx::optional<mongocxx::result::insert_many> insert_many_result = collection.insert_many(documents);
if(insert_many_result) {
std::cout << "\ninsert " << insert_many_result->inserted_count() << " documents:\n";
}
mongocxx::result::insert_many::id_map idMap = insert_many_result->inserted_ids();
for (auto ele : idMap) {
auto idx = ele.first;
auto id = ele.second.get_oid().value.to_string();
std::cout << "index: " << idx << " <--> id: " << id << std::endl;
}
// --------------------------------------------------------------
// 查询单个文档
bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result = collection.find_one({});
bsoncxx::document::view view2 = maybe_result->view();
auto find_one_id = view2["_id"].get_oid().value.to_string();
std::cout << "\nfind one document, return id is " << find_one_id << std::endl;
// 查询所有文档
std::cout << "\nfind all documents, return values:\n";
mongocxx::cursor cursor = collection.find({});
for(bsoncxx::document::view docView : cursor) {
std::cout << bsoncxx::to_json(docView) << std::endl;
}
// 查询匹配过滤器的单个文档
// 为了获取字段 i 为 7 的第一个文档,传递文档 {"i":7} 来指定等式条件:
bsoncxx::stdx::optional<bsoncxx::document::value> find_one_result =
collection.find_one(document{} << "i" << 7 << finalize);
if(find_one_result) {
std::cout << "\nspecify query filter, find_one() return values: \n";
std::cout << bsoncxx::to_json(find_one_result->view()) << std::endl;
// std::cout << bsoncxx::to_json(*find_one_result) << std::endl;
// 输出 { "_id" : { "$oid" : "5755e19b38c96f1fb25667a8" }, "i" : 71 }
// _id 字段是被MongoDB自动添加上的。MongoDB保留字段名称以一个下划线(_)和美元符号($)开始,用于内部使用。
}
// 查询匹配过滤器的多个文档,匹配同时满足以下条件为:
// 1) 5 < i <= 10
// 2) 按 i 降序排序
// 3) 只返回 i 字段
// 4) 只返回前 3 个值
std::cout << "\nspecify query filter, find() return values:\n";
auto filter = document{} << "i" << open_document <<
"$gt" << 5 << "$lte" << 10 << close_document << finalize;
auto order = document{} << "i" << -1 << finalize;
auto field = document{} << "_id" << 0 << "i" << 1 << finalize;
mongocxx::options::find opts = mongocxx::options::find{};
opts.sort(order.view()).projection(field.view()).limit(3);
mongocxx::cursor cur = collection.find(filter.view(), opts);
for(bsoncxx::document::view docView : cur) {
std::cout << bsoncxx::to_json(docView) << std::endl;
}
// --------------------------------------------------------------
// 更新单个文档
mongocxx::stdx::optional<mongocxx::result::update> update_one_result =
collection.update_one(document{} << "i" << 0 << finalize,
document{} << "$set" << open_document <<
"i" << 100 << close_document << finalize);
// 更新多个文档
bsoncxx::stdx::optional<mongocxx::result::update> update_many_result =
collection.update_many(
document{} << "i" << open_document <<
"$lt" << 10 << close_document << finalize,
document{} << "$inc" << open_document <<
"i" << 10 << close_document << finalize);
if(update_many_result) {
std::cout << "\nupdate " << update_many_result->modified_count() << " documents\n";
}
std::cout << "collection after update:\n";
cursor = collection.find({});
for(bsoncxx::document::view docView : cursor) {
std::cout << bsoncxx::to_json(docView) << std::endl;
}
// --------------------------------------------------------------
// 删除单个文档
mongocxx::stdx::optional<mongocxx::result::delete_result> delete_one_result =
collection.delete_one(document{} << "i" << 100 << finalize);
if (delete_one_result) {
std::cout << "\ndelete " << delete_one_result->deleted_count() << " document\n";
}
// 删除匹配过滤器的所有文档
// 删除所有 i 值大于 5 的文档
bsoncxx::stdx::optional<mongocxx::result::delete_result> delete_many_result =
collection.delete_many(
document{} << "i" << open_document <<
"$gte" << 15 << close_document << finalize);
if(delete_many_result) {
std::cout << "delete " << delete_many_result->deleted_count() << " documents\n";
}
std::cout << "collection after deiete:\n";
cursor = collection.find({});
for(bsoncxx::document::view docView : cursor) {
std::cout << bsoncxx::to_json(docView) << "\n";
}
// --------------------------------------------------------------
// 创建索引(Indexes)
// 按照 i 字段升序的方式建立索引
auto index_specification = document{} << "i" << 1 << finalize; // 升序1,降序-1
bsoncxx::document::value val = collection.create_index(std::move(index_specification));
std::cout << "\ncreate index result:" << std::endl;
std::cout << bsoncxx::to_json(val.view()) << std::endl;
}
输出:
name: MongoDB
version:
v1.0 v2.0 v3.0
info:
x: 1314
y: 520
Insert one document, return id is 5fdf0b640c1ab7666977cd02
insert 10 documents:
index: 0 <--> id: 5fdf0b640c1ab7666977cd03
index: 1 <--> id: 5fdf0b640c1ab7666977cd04
index: 2 <--> id: 5fdf0b640c1ab7666977cd05
index: 3 <--> id: 5fdf0b640c1ab7666977cd06
index: 4 <--> id: 5fdf0b640c1ab7666977cd07
index: 5 <--> id: 5fdf0b640c1ab7666977cd08
index: 6 <--> id: 5fdf0b640c1ab7666977cd09
index: 7 <--> id: 5fdf0b640c1ab7666977cd0a
index: 8 <--> id: 5fdf0b640c1ab7666977cd0b
index: 9 <--> id: 5fdf0b640c1ab7666977cd0c
find one document, return id is 5fdf0b640c1ab7666977cd02
find all documents, return values:
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd02" }, "name" : "MongoDB", "type" : "database", "count" : 1, "versions" : [ "v1.0", "v2.0", "v3.0" ], "info" : { "x" : 1314, "y" : 520 } }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd03" }, "i" : 0 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd04" }, "i" : 1 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd05" }, "i" : 2 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd06" }, "i" : 3 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd07" }, "i" : 4 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd08" }, "i" : 5 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd09" }, "i" : 6 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0a" }, "i" : 7 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0b" }, "i" : 8 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0c" }, "i" : 9 }
specify query filter, find_one() return values:
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0a" }, "i" : 7 }
specify query filter, find() return values:
{ "i" : 9 }
{ "i" : 8 }
{ "i" : 7 }
update 9 documents
collection after update:
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd02" }, "name" : "MongoDB", "type" : "database", "count" : 1, "versions" : [ "v1.0", "v2.0", "v3.0" ], "info" : { "x" : 1314, "y" : 520 } }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd03" }, "i" : 100 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd04" }, "i" : 11 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd05" }, "i" : 12 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd06" }, "i" : 13 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd07" }, "i" : 14 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd08" }, "i" : 15 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd09" }, "i" : 16 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0a" }, "i" : 17 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0b" }, "i" : 18 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd0c" }, "i" : 19 }
delete 1 document
delete 5 documents
collection after deiete:
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd02" }, "name" : "MongoDB", "type" : "database", "count" : 1, "versions" : [ "v1.0", "v2.0", "v3.0" ], "info" : { "x" : 1314, "y" : 520 } }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd04" }, "i" : 11 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd05" }, "i" : 12 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd06" }, "i" : 13 }
{ "_id" : { "$oid" : "5fdf0b640c1ab7666977cd07" }, "i" : 14 }
create index result:
{ "name" : "i_1" }
参考: