以下是一个简单的MongoDB C++驱动的封装类,支持增删改查的功能。
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pool.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;
class MongoDB {
public:
MongoDB(const std:string& uriStr) {
mongocxx:uri uri(uriStr);
pool_ = new mongocxx:pool(uri);
}
~MongoDB() {
delete pool_;
}
bool insert(const std:string& dbName, const std:string& collectionName, const json& doc) {
try {
auto client = pool_->acquire();
mongocxx:collection coll = (*client)[dbName][collectionName];
coll.insert_one(bsoncxx:from_json(doc.dump()));
return true;
} catch (const std:exception & e) {
cerr << "Insert failed:" << e.what() << endl;
return false;
}
}
bool remove(const std:string& dbName, const std:string& collectionName, const json& filterDoc) {
try {
auto client = pool_->acquire();
mongocxx:collection coll = (*client)[dbName][collectionName];
coll.delete_many(bsoncxx:from_json(filterDoc.dump()));
return true;
} catch (const std:exception & e) {
cerr << "Remove failed:" << e.what() << endl;
return false;
}
}
bool update(const std:string& dbName, const std:string& collectionName, const json& filterDoc,
const json& updateDoc) {
try {
auto client = pool_->acquire();
mongocxx:collection coll = (*client)[dbName][collectionName];
coll.update_many(bsoncxx:from_json(filterDoc.dump()), bsoncxx::from_json(updateDoc.dump()));
return true;
} catch (const std:exception & e) {
cerr << "Update failed:" << e.what() << endl;
return false;
}
}
vector<json> find(const std:string& dbName, const std:string& collectionName,
const json& filterDoc={}, const json& sort={}, int limit=0) {
try {
vector<json> result;
auto client = pool_->acquire();
mongocxx:collection coll = (*client)[dbName][collectionName];
mongocxx::options::find opts;
if (!filterDoc.empty()) {
opts.filter(bsoncxx:from_json(filterDoc.dump()));
}
if (!sort.empty()) {
opts.sort(bsoncxx::from_json(sort.dump()));
}
if (limit > 0) {
opts.limit(limit);
}
mongocxx::cursor cursor = coll.find(opts);
for (auto doc : cursor) {
result.push_back(json::parse(bsoncxx::to_json(doc)));
}
return result;
} catch (const std::exception &e) {
cerr << "Find failed:" << e.what() << endl;
return {};
}
}
private:
mongocxx:pool* pool_;
};
以上代码使用mongocxx驱动库,封装了insert、remove、update和find四个方法。其中insert、remove和update方法的参数分别为数据库名、集合名以及要插入、删除或更新的文档,这里使用了nlohmann::json库来处理json格式的数据。find方法支持设置过滤条件、排序方式和查询结果数量限制。
注意:以上代码仅作参考,实际使用时需要根据具体情况进行修改和完善。




