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;
}