mongDB的c++调用

https://blog.csdn.net/Zhuxiaoyu_91/article/details/135048070?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1-135048070-blog-119898922.235^v43^pc_blog_bottom_relevance_base5&spm=1001.2101.3001.4242.2&utm_relevant_index=4

1、下载驱动程序源码,并编译。

<https://github.com/mongodb/mongo-cxx-driver/>

cmake只修改了install路径

之前遇到过一个bsoncxx-v_noabi-rhs-找不到的问题,但是后来一直也没遇到,有问题在参考吧。

参考https://www.mongodb.com/community/forums/t/very-strange-dll-names-in-mongo-cxx-driver-3-11-0-with-vs2022/301340/2 解决了ENABLE_ABI_TAG_IN_LIBRARY_FILENAMES=OFF

2、启动服务

windows:
exec/mongod --port=27017 --dbpath=data --logpath=log/mongodb.log  --bind_ip=0.0.0.0

或者创建config文件

systemLog:
  destination: file
  path: ./log/mongod.log # log path
  logAppend: true
storage:
  dbPath: ./data # data directory
  engine: wiredTiger  #存储引擎
net:
  bindIp: 0.0.0.0
  port: 27017 # port
exec/mongod -f conf/mongo.conf

关闭

mongod --port=27017 --dbpath=/mongodb/data --shutdown 

3、配置cmake

set(CMAKE_PREFIX_PATH  ${mongodb_path} ${CMAKE_PREFIX_PATH})
message(STATUS ${CMAKE_PREFIX_PATH} )
# Find MongoDB C++ driver (requires mongocxx and its dependencies)
find_package(mongocxx REQUIRED)
find_package(bsoncxx REQUIRED)

add_executable(mongo_test main.cpp)

# Link against mongocxx and bsoncxx
target_link_libraries(mongo_test
   PRIVATE
   mongo::mongocxx_shared
   mongo::bsoncxx_shared
)
configure_file(${mongodb_path}/bin/mongocxx-v_noabi-dhi-x64-v143-mdd.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/mongocxx-v_noabi-dhi-x64-v143-mdd.dll COPYONLY)
configure_file(${mongodb_path}/bin/bsoncxx-v_noabi-dhi-x64-v143-mdd.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/bsoncxx-v_noabi-dhi-x64-v143-mdd.dll COPYONLY)
configure_file(${mongodb_path}/bin/mongoc-1.0.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/mongoc-1.0.dll COPYONLY)
configure_file(${mongodb_path}/bin/bson-1.0.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/bson-1.0.dll COPYONLY)

4、设置调用测试

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

int main() {
    mongocxx::instance instance{}; // Initialize the MongoDB driver
    mongocxx::client client{mongocxx::uri{}};

    auto db = client["test_db"];
    auto collection = db["test_collection"];

    // Insert a document
    bsoncxx::builder::stream::document document{};
    document << "name" << "ChatGPT"
             << "type" << "AI"
             << "year" << 2024;

    collection.insert_one(document.view());

    // Query documents
    auto cursor = collection.find({});
    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值