提示:以下是本篇文章正文内容,下面案例可供参考
#pragma once
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::make_array;
static mongocxx::pool *s_pool = nullptr;
bool mongoInit() {
static mongocxx::instance inst{};
mongocxx::uri uri{"mongodb://127.0.0.1:27017/?minPoolSize=0&maxPoolSize=100"};
s_pool = new mongocxx::pool(uri);
auto client = s_pool->acquire();
return (bool)client;
}
void mongoQuit() {
delete s_pool;
s_pool = nullptr;
}
mongocxx::pool::entry mongoClient() {
return s_pool->acquire();
}
CRUD
插入数据
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
auto location= (*client)["places"]["location"];
auto sites= (*client)["places"]["sites"];
auto builder = document{};
auto coordinates = bsoncxx::builder::stream::array{};
coordinates << 1 << 1;
builder<< "type"<< "Point" <<"coordinates" << coordinates;
auto docvalue = builder << finalize;
auto doc_value = builder<< "name" << "Central Park"
<< "category" << "Parks"
<< "location" << docvalue << finalize;
auto doc_value2 = builder << "name" << "MidCentral Park"
<< "category" << "House"
<< "count" << 1
<< "modifydate" << open_array << "2022" << "2023" << "2024" << close_array
<< "position" << open_document << "x" << 203 << "y" << 102 << close_document
<< "createdate" << open_array
<< open_document<< "year"<< 2022<< "month" << 02<< "day" << 22 << close_document
<< open_document<< "year" << 2021<< "month" << 01<< "day" << 21 << close_document
<< close_array
<< finalize;
std::vector<bsoncxx::document::value> documents;
for(int i=0;i<3;i++){
documents.push_back(document{}
<< "name" << "My House"
<< "category" << "house"
<< "location" << "SH PuDong"
<< finalize);
}
try {
places.insert_one(doc_value.view());
location.insert_one(doc_value2.view()); //插入一条数据
sites.insert_many(documents); //插入多条数据
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
}
mongoQuit();
查询数据
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
auto location= (*client)["places"]["location"];
auto builder = document{};
auto doc_value = builder<< "name" << "MidCentral Park" << finalize;
mongocxx::cursor results = places.find({});
bsoncxx::stdx::optional<bsoncxx::document::value> results2 = location.find_one(doc_value.view());
for (const bsoncxx::document::view &result: results) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
if (results2 ){
const bsoncxx::document::view &view = results2 ->view();
std::cout << "location is " << view["_id"].get_oid().value.to_string()<< std::endl;
if(view.find("modifydate") != docView.end()){
const bsoncxx::array::view &dates= view["modifydate"].get_array().value;
for (bsoncxx::array::element &date: dates) {
std::cout<< date.get_utf8().value.to_string()<<std::endl;
}
}
}
//统计数量
int pagesize= 10;
int pageIndex = 0;
int64_t dwnum = location.count_documents({}); //查询数据总数
int32_t pagenumer = dwnum / pagesize; //用于计算分页数量
//用于分页查询使用
mongocxx::options::find opts = mongocxx::options::find{};
auto order = document{} << "name" << 1 << finalize; //name的值、升序或者降序排列
opts.sort(order.view()).skip(pageindex* pagesize).limit(pagesize);
auto filter = document{} << "category" << "Parks" << finalize;
mongocxx::cursor results3 = location.find(filter.view(), opts);
for (const bsoncxx::document::view &result: results3 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
//或条件查询
auto filter2 = document{} << "$or" << open_array
<< open_document << "name" << "Central Park" << close_document
<< open_document << "category" << "Parks" << close_document << close_array
<< finalize;
mongocxx::cursor results3 = places.find(filter2.view());
for (const bsoncxx::document::view &result: results3 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
auto filter3 = document{} << "name" << open_document
<< "$ne" << "Central Park"
<< close_document << finalize;
mongocxx::cursor results4 = places.find(filter3.view());
for (const bsoncxx::document::view &result: results4 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
//模糊查询、不区分大小写
auto filtername = "Central";
auto filter4 = open_document << "name" << open_document
<< "$regex" << filtername
<< "$options" << "i"
<< close_document << finalize;
mongocxx::cursor results5 = places.find(filter4 .view());
for (const bsoncxx::document::view &result: results5 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
auto alarmtimebegin = 1;
auto alarmtimeend = 10;
auto filter5 = document{} << "createdate" << open_document
<< "$gte" << timebegin << "$lt" << timeend
<< close_document
<< finalize;
mongocxx::cursor results6 = location.find(filter5.view());
for (const bsoncxx::document::view &result: results6 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
//in 条件查询
auto deviceids[] = {1,2,3,4};
auto builder = document{};
auto ids = bsoncxx::builder::stream::array{};
for (auto deviceid : deviceids) {
ids << deviceid;
}
auto filter6 = builder << "id" << open_document << "$in" << ids << close_document << finalize;
mongocxx::cursor results7 = location.find(filter6.view());
for (const bsoncxx::document::view &result: results7 ) {
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
mongoQuit();
更新数据
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
auto location= (*client)["places"]["location"];
auto builder = document{};
auto doc_value = builder << "category" << "Parks 2" << finalize;
mongocxx::options::update updopts{};
updopts.upsert(true); //当doc不存在时,会存入数据
auto result = places.update_one(document{} << "name" << "Central Park" << finalize,
doc_value.view(),updopts);
auto result2 = location.update_many(document{} << "count" << open_document << "$lt" << 100 << close_document << finalize);
if (!result) {
std::cout<< "update failed"<<std::endl;
}
if (!result2) {
std::cout<< "update2 failed"<<std::endl;
}
mongoQuit();
删除数据
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
auto builder = document{};
auto doc_value = builder<< "name" << "Central Park" << "category" << "Parks" << finalize;
auto doc_value2 = document{} << "name" << open_document
<< "$ne" << "Central Park"
<< close_document << finalize;
auto doc_value3 = document{} << "$or" << open_array
<< open_document << "name" << "Central Park" << close_document
<< open_document << "category" << "Parks" << close_document << close_array
<< finalize;
auto doc_value4 = builder<< "category" << "Parks" << finalize;
try {
places.delete_one(doc_value.view());
places.delete_one(doc_value2.view());
places.delete_one(doc_value3.view());
places.delete_many(doc_value4.view()); //删除多个case
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
}
mongoQuit();
高级操作
多边形查询,圆形查询
参考如下方式实现
db.places.find({
location:
{$geoWithin:{
$geometry:{type:"Polygon",coordinates:[[[0,2],[2,2],[2,0],[0,0],[0,2]]]}
}}
})
db.places.find({
location:{ $near:{
$geometry: { type: "Point", coordinates: [ 1, 1 ] },
$minDistance: 0,
$maxDistance: 100000
}
}})
db.places.find( {
location: { $geoWithin: { $centerSphere: [ [ 1, 1 ], (300000/1609)/3963.2 ] } }
} )
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
int coordinatedata[5][2] = {{0,2},{2,2},{2,0},{0,0},{0,2},};
auto builder = document{};
auto mutilcoordinates = bsoncxx::builder::stream::array{};
auto coordinates = bsoncxx::builder::stream::array{};
for(int i=0;i<5;i++){
auto xy = bsoncxx::builder::stream::array{};
xy << coordinatedata[i][0] << coordinatedata[i][1];
coordinates<< xy;
}
mutilcoordinates<< coordinates;
builder<< "type"<< "Polygon" <<"coordinates" << mutilcoordinates;
auto doc_value = builder << finalize;
auto results = places.find(document{} << "location" << open_document << "$geoWithin" << open_document << "$geometry" << doc_value << close_document << close_document << finalize);
for(const auto &result:results){
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
mongoQuit();
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
int x = 1;
int y = 1;
auto builder = document{};
auto point = bsoncxx::builder::stream::array{};
point << x << y;
builder<< "type"<< "Point" <<"coordinates" << point;
auto doc_value = builder << finalize;
auto results = places.find(document{} << "location" << open_document << "$near" << open_document << "$geometry" << doc_value << "$minDistance" << 0 << "$maxDistance" << 300000 << close_document << close_document << finalize);
for(const auto &result:results){
std::cout<< "polygon query name: "<< result["name"].get_utf8().value.to_string() << "category: "<< result["category"].get_utf8().value.to_string() <<std::endl;
}
auto builder2 = document{};
auto point2 = bsoncxx::builder::stream::array{};
auto centersphere = bsoncxx::builder::stream::array{};
point2 << x << y;
centersphere << point2;
centersphere << (300000/1609)/3963.2;
builder2 << "location" << open_document << "$geoWithin" << open_document << "$centerSphere" << centersphere << close_document << close_document;
auto doc_value2 = builder2 << finalize;
auto results4 = places.find(doc_value2.view());
for(const auto &result:results4){
std::cout<< "circle2 query name: "<< result["name"].get_utf8().value.to_string() <<std::endl;
}
mongoQuit();
聚合操作
参考如下方式实现
db.getCollection('runoob').aggregate(
{"$match":{"date": {'$gte':1667232000,'$lt':1667923200},"url":"http://www.runoob.com"}}
,{"$group": {
"_id": { "$subtract": [
{ "$subtract": [ "$date", 1667232000] },
{ "$mod": [{ "$subtract": [ "$date", 1667232000 ] },3600]}
]},
"total": {'$sum': 1}
}}
,{"$project": {
"_id": 1,
"count":1,
'datetime': {'$add': [1667232000, '$_id']}
}}
,{"$sort": {
'datetime': 1
}}
)
mongoInit();
auto client=mongoClient();
auto places = (*client)["places"]["places"];
long fromdate=1667232000;
long enddate= 1667923200;
std::string url = "http://www.runoob.com";
auto filter = document{}<< "url" << url << "dt" << open_document << "$gte" << fromdate << "$lt" << enddate << close_document<< finalize;
mongocxx::pipeline pipelineInst;
pipelineInst.match(filter.view())
.group(make_document(kvp("_id",
make_document(kvp("$subtract", make_array( make_document(kvp("$subtract", make_array("$dt", fromdate))),
make_document(kvp("$mod", make_array(make_document(kvp("$subtract", make_array("$dt", fromdate))) , statisticunit())))
))) ),
kvp("count", make_document(kvp("$sum", 1)))
))
.project(make_document(kvp("_id", 1),kvp("count",1),kvp("datetime",
make_document(kvp("$add", make_array(fromdate, "$_id"))))
));
int total = 0;
int topVal = 0;
for (const auto& result_place : result_places) {
int64_t count = result_place["count"].get_int32().value;
int64_t id = result_place["_id"].get_int64().value;
total += count;
if(count> topVal)
topVal = count;
}
std::cout<< "total: "<< total << " topVal:"<< topVal <<std::endl;
mongoQuit();
本文介绍了一些常用c++ mongo driver之crud的用法与高级用法,希望对你有所帮助。
老铁:如果觉得还不错,别忘了随手点赞转发+关注哦!