連接 MongoDB 數(shù)據(jù)庫使用 C++,可以通過 MongoDB 的 C++ 驅(qū)動程序來實現(xiàn)。以下是連接 MongoDB 數(shù)據(jù)庫的步驟:
安裝 MongoDB 的 C++ 驅(qū)動程序??梢酝ㄟ^官方網(wǎng)站下載并安裝 C++ 驅(qū)動程序。
在 C++ 項目中包含 MongoDB 驅(qū)動程序的頭文件。通常情況下,可以使用以下 include 語句:
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
mongocxx::instance inst{};
mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
其中,mongodb://localhost:27017
是 MongoDB 數(shù)據(jù)庫的連接字符串,localhost
是數(shù)據(jù)庫主機(jī)名,27017
是數(shù)據(jù)庫端口號。
auto collection = client["mydb"]["mycollection"];
auto cursor = collection.find({});
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
這樣就可以在 C++ 程序中連接到 MongoDB 數(shù)據(jù)庫并執(zhí)行操作了。