c++连接mongocxx,将代码进行类封装

发布时间 2023-05-30 08:23:43作者: 我当道士那儿些年

 

这里需要注意一个事情,就是instance必须变成全局类

#ifndef GET_DATA_HPP
#define GET_DATA_HPP

#include <iostream>
#include <string>
#include <vector>

#include "conf.hpp"
#include <nlohmann/json.hpp>
using json = nlohmann::json;

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>

#include <stdio.h>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;

// 实例化 mongocxx::instance 对象,必须变成全局类
static mongocxx::instance instance{};

mongocxx::client get_mongo_client() {
    // 先获取数据库信息,用于链接数据库用
    json mongo_infor;
    mongo_infor = get_mongo_conf();
    //std::cout << mongo_infor << std::endl;

    string mongo_infor_host = mongo_infor["host"];
    string mongo_infor_port = mongo_infor["port"];
    //std::cout << mongo_infor_host << std::endl;
    //std::cout << mongo_infor_port << std::endl;

    // "mongodb://localhost:27017" 拼接链接Mongo的字符串
    string mongo_uri = "mongodb://" + mongo_infor_host + ':' + mongo_infor_port;
    std::cout << mongo_uri << std::endl;

    // 链接mongo
    // instance变成全局的了,要不报错
    // mongocxx::instance inst{}; // 实例化 Mongocxx 库
    // mongocxx::uri uri("mongodb://localhost:27017"); // 连接 MongoDB URI
    mongocxx::uri uri(mongo_uri); // 连接 MongoDB URI
    mongocxx::client client(uri); // 创建连接实例
    return client;
}

mongocxx::database get_mongo_db(mongocxx::client& client, std::string& db_name) {
    // 先获取数据库信息,用于链接数据库用
    json mongo_infor;
    mongo_infor = get_mongo_conf();
    string mongo_infor_data_db = mongo_infor[db_name];  //data_base_information
    // std::cout << mongo_infor_data_db << std::endl;
    auto db = client[mongo_infor_data_db]; // 获取集合
    return db;
}


mongocxx::collection get_mongo_collection(mongocxx::database& db_name, const std::string& collection_name) {

    return db_name[collection_name];
}



int get_mongo_cursor(mongocxx::collection& collection) {

    // 获取表名,一个数据存了多少个表(因为数据量比较大,所以需要进行数据拆分)
    // 查询文档
    // 构造查询条件
    string mycolumn_name = "teacher_20230417";

    auto cursor = collection.find(document{} << finalize);
    std::cout << "column_value" << mycolumn_name << std::endl;

    for (auto& doc : cursor) {
        auto column_value = doc["teacher_20230417"].get_utf8().value.to_string();
        std::cout << column_value << std::endl;

    }
    return 0;

}




int get_data_infor_table() {

    mongocxx::client client;
    client = get_mongo_client();

    mongocxx::database db;
    std::string db_name = "db_infor";
    db = get_mongo_db(client, db_name);

    mongocxx::collection collection;
    std::string  coll_table_name = "teacher_20230417";
    coll_table_name = coll_table_name + "_table_infor";
    collection = get_mongo_collection(db, coll_table_name);

    get_mongo_cursor(collection);


    return 0;
}







#endif // GET_DATA_HPP