以下是一个基本的MongoDB C++驱动封装接口,包括增删改查的功能:
#include <mongoc.h>
class MongoDB {
public:
MongoDB(const std::string& uri_str, const std::string& db_name)
: client_{mongoc_client_new(uri_str.c_str())},
db_{mongoc_client_get_database(client_, db_name.c_str())} {}
~MongoDB() {
mongoc_database_destroy(db_);
mongoc_client_destroy(client_);
}
bool insert(const std::string& collection_name, const bson_t* doc) {
mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
bson_error_t error;
bool success = mongoc_collection_insert_one(coll, doc, nullptr, nullptr, &error);
if (!success) {
// handle error
return false;
}
return true;
}
bool update(const std::string& collection_name, const bson_t* filter, const bson_t* update) {
mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
bson_error_t error;
bool success = mongoc_collection_update_one(coll, filter, update, nullptr, &error);
if (!success) {
// handle error
return false;
}
return true;
}
bool remove(const std::string& collection_name, const bson_t* filter) {
mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
bson_error_t error;
bool success = mongoc_collection_delete_one(coll, filter, nullptr, &error);
if (!success) {
// handle error
return false;
}
return true;
}
mongoc_cursor_t* query(const std::string& collection_name, const bson_t* filter) {
mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
return mongoc_collection_find_with_opts(coll, filter, nullptr, nullptr);
}
private:
mongoc_client_t* client_;
mongoc_database_t* db_;
};
使用时,可以先创建一个MongoDB对象,并传入URI字符串和数据库名称:
std::string uri_str = "mongodb://localhost:27017";
std::string db_name = "test";
MongoDB mongo{uri_str, db_name};
然后就可以进行增删改查操作了。例如插入一个文档:
bson_t doc;
bson_init(&doc);
BSON_APPEND_UTF8(&doc, "name", "Alice");
BSON_APPEND_INT32(&doc, "age", 25);
mongo.insert("users", &doc);
bson_destroy(&doc);
查询所有文档并遍历输出结果:
mongoc_cursor_t* cursor = mongo.query("users", nullptr);
const bson_t* doc;
while (mongoc_cursor_next(cursor, &doc)) {
char* str = bson_as_json(doc, nullptr);
std::cout << str << std::endl;
bson_free(str);
}
mongoc_cursor_destroy(cursor);