连接到 MongoDB
1
2
创建您的C++驱动程序应用程序
将以下代码复制并粘贴到quickstart.cpp
文件中,该文件查询movies
集合在sample_mflix
数据库中
#include <cstdint> #include <iostream> #include <vector> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/uri.hpp> using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance; mongocxx::uri uri("<connection string>"); mongocxx::client client(uri); auto db = client["sample_mflix"]; auto collection = db["movies"]; auto result = collection.find_one(make_document(kvp("title", "The Shawshank Redemption"))); std::cout << bsoncxx::to_json(*result) << std::endl; }
3
将连接字符串
将<connection string>
占位符替换为您从本指南的创建连接字符串步骤中复制的连接字符串。
4
运行您的C++应用程序
在您的shell中,运行以下命令以编译和运行此应用程序
c++ --std=c++17 quickstart.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
提示
MacOS用户在运行上述命令后可能会看到以下错误
dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
要解决此错误,请使用-Wl,-rpath
链接器选项设置@rpath
,如下面的代码所示
c++ --std=c++17 quickstart.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
命令行输出包含检索到的电影文档的详细信息
{ "_id" : { "$oid" : "573a1399f29313caabceeb20" }, "plot" : "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", ... "title" : "The Shawshank Redemption", ...
如果您遇到错误或没有输出,请确保在quickstart.cpp
文件中指定了正确的连接字符串,并且已经加载了示例数据。
完成这些步骤后,您将拥有一个正常工作的应用程序,该应用程序使用驱动程序连接到您的MongoDB部署,在示例数据上运行查询,并打印结果。
注意
如果您在这个步骤遇到问题,请在MongoDB社区论坛寻求帮助或通过使用评价此页面标签在页面右侧或右下角提交反馈。