ZBLOG

给出一个完整的cpp类,操作mongodb

下面是一个完整的 C++ 类示例,使用 MongoDB C++ 驱动程序操作 MongoDB 数据库。这个类名为 MongoClient,它封装了基本的连接、插入和查询功能。

安装 MongoDB C++ 驱动

首先,确保您已安装 MongoDB C++ 驱动程序。在 Linux 上可以使用以下命令:

sudo apt-get install libmongocxx-dev libbsoncxx-dev

请根据您的系统和环境查找适合的安装方法。

MongoClient.h

#ifndef MONGOC_CLIENT_H
#define MONGOC_CLIENT_H

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pool.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>

#include <iostream>
#include <string>

class MongoClient {
public:
    MongoClient(const std::string& uri);
    ~MongoClient();

    bool insertDocument(const std::string& db_name, const std::string& collection_name, const bsoncxx::document::value& document);
    bsoncxx::document::value findDocument(const std::string& db_name, const std::string& collection_name, const bsoncxx::document::value& query);

private:
    mongocxx::instance instance_;
    mongocxx::client client_;
};

#endif // MONGOC_CLIENT_H

MongoClient.cpp

#include "MongoClient.h"

MongoClient::MongoClient(const std::string& uri)
    : client_(mongocxx::uri{uri}) {
}

MongoClient::~MongoClient() {
}

bool MongoClient::insertDocument(const std::string& db_name, const std::string& collection_name, const bsoncxx::document::value& document) {
    try {
        auto collection = client_[db_name][collection_name];
        collection.insert_one(document.view());
        return true;
    } catch (const std::exception &e) {
        std::cerr << "Insert error: " << e.what() << std::endl;
        return false;
    }
}

bsoncxx::document::value MongoClient::findDocument(const std::string& db_name, const std::string& collection_name, const bsoncxx::document::value& query) {
    try {
        auto collection = client_[db_name][collection_name];
        auto result = collection.find_one(query.view());

        if (result) {
            return *result; // 返回找到的文档
        } else {
            throw std::runtime_error("No document found");
        }
    } catch (const std::exception &e) {
        std::cerr << "Find error: " << e.what() << std::endl;
        return {};
    }
}

main.cpp

这是一个示例程序,展示如何使用 MongoClient 类:

#include "MongoClient.h"

int main() {
    // 创建一个 MongoDB 客户端连接 URI(根据需要更改)
    const std::__1::__basic_string<char> uri = "mongodb://localhost:27017";
    
    // 初始化数据库客户端
  	MongoClient mongo_client(uri);

  	// 构建要插入的文档
  	bsoncxx :: builder :: stream :: document builder ;
  	auto doc_value = builder 
      .append(bsoncxx :: builder :: stream :: kvp("name", "Alice"),
              bsoncxx :: builder :: stream :: kvp("age", 30),
              bsoncxx :: builder :: stream :: kvp("city", "New York"))
      .extract();
    
  	// 插入文档到数据库中 
	if (!mongo_client.insertDocument("test_db", "test_collection", doc_value)) { 
      	return -1; // 插入错误 
	} 
	
	std :: cout << "Inserted document successfully" <<std :: endl;

  	// 构建查询条件 
	bsoncxx : : builder : : stream : : document query_builder ;
	auto query_value = query_builder.append(bsoncxx :: builder ::
	  stream ::: kvp ("name", "Alice")).extract(); 

	auto result_doc = mongo_client.findDocument("test_db", "test_collection", query_value); 
	
	if (!result_doc.is_null()) { 
      	std : : cout <<"Found document: "<<bsoncxxxjson(result_doc.view())<<std ::: endl;  
	} else { 
      	std : : cout <<"No document found"<<std ::: endl;  
	} 

	return 0; 
}

编译与运行

确保您在编译时链接了 MongCXX 和 BSONCXX 库,可以使用以下命令:

g++ -o mongo_client main.cpp MongoClient.cpp $(pkg-config --cflags --libs libmongocXX)

请确保在运行之前启动了您的 MongoDB 服务,并根据实际情况调整代码中的 URI 和数据库名称。

该代码提供了一个简单但完整的 C++ 类,用于与 MongoDB 进行基本的交互,包括插入和查询操作。如果需要更复杂的操作,可以继续扩展此类。


内容由零声教学AI助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?