ZBLOG

mongodb c的驱动封装接口,封装采用c++的写法,支持增删改查的功能

以下是一个基本的MongoDB C++驱动封装接口,包括增删改查的功能:

  1. #include <mongoc.h>
  2. class MongoDB {
  3. public:
  4. MongoDB(const std::string& uri_str, const std::string& db_name)
  5. : client_{mongoc_client_new(uri_str.c_str())},
  6. db_{mongoc_client_get_database(client_, db_name.c_str())} {}
  7. ~MongoDB() {
  8. mongoc_database_destroy(db_);
  9. mongoc_client_destroy(client_);
  10. }
  11. bool insert(const std::string& collection_name, const bson_t* doc) {
  12. mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
  13. bson_error_t error;
  14. bool success = mongoc_collection_insert_one(coll, doc, nullptr, nullptr, &error);
  15. if (!success) {
  16. // handle error
  17. return false;
  18. }
  19. return true;
  20. }
  21. bool update(const std::string& collection_name, const bson_t* filter, const bson_t* update) {
  22. mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
  23. bson_error_t error;
  24. bool success = mongoc_collection_update_one(coll, filter, update, nullptr, &error);
  25. if (!success) {
  26. // handle error
  27. return false;
  28. }
  29. return true;
  30. }
  31. bool remove(const std::string& collection_name, const bson_t* filter) {
  32. mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
  33. bson_error_t error;
  34. bool success = mongoc_collection_delete_one(coll, filter, nullptr, &error);
  35. if (!success) {
  36. // handle error
  37. return false;
  38. }
  39. return true;
  40. }
  41. mongoc_cursor_t* query(const std::string& collection_name, const bson_t* filter) {
  42. mongoc_collection_t* coll = mongoc_client_get_collection(client_, db_name_.c_str(), collection_name.c_str());
  43. return mongoc_collection_find_with_opts(coll, filter, nullptr, nullptr);
  44. }
  45. private:
  46. mongoc_client_t* client_;
  47. mongoc_database_t* db_;
  48. };

使用时,可以先创建一个MongoDB对象,并传入URI字符串和数据库名称:

  1. std::string uri_str = "mongodb://localhost:27017";
  2. std::string db_name = "test";
  3. MongoDB mongo{uri_str, db_name};

然后就可以进行增删改查操作了。例如插入一个文档:

  1. bson_t doc;
  2. bson_init(&doc);
  3. BSON_APPEND_UTF8(&doc, "name", "Alice");
  4. BSON_APPEND_INT32(&doc, "age", 25);
  5. mongo.insert("users", &doc);
  6. bson_destroy(&doc);

查询所有文档并遍历输出结果:

  1. mongoc_cursor_t* cursor = mongo.query("users", nullptr);
  2. const bson_t* doc;
  3. while (mongoc_cursor_next(cursor, &doc)) {
  4. char* str = bson_as_json(doc, nullptr);
  5. std::cout << str << std::endl;
  6. bson_free(str);
  7. }
  8. mongoc_cursor_destroy(cursor);

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=6081

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?