温馨提示×

c++中mongodb的使用案例

c++
小樊
87
2024-08-11 04:40:36
栏目: 云计算

在C++中使用MongoDB可以通过MongoDB的C++驱动程序实现。以下是一个简单的示例,演示如何在C++中连接到MongoDB数据库并插入数据:

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

int main() {
    // 创建MongoDB客户端
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{}};

    // 获取数据库和集合
    auto db = client["mydb"];
    auto collection = db["mycollection"];

    // 插入数据
    bsoncxx::builder::stream::document document{};
    document << "name" << "Alice"
             << "age" << 30;
    
    collection.insert_one(document.view());

    // 查询数据
    auto cursor = collection.find({});
    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

在上面的示例中,我们首先创建了一个MongoDB客户端,然后连接到名为“mydb”的数据库和名为“mycollection”的集合。接下来,我们插入了一个包含姓名和年龄字段的文档,并通过查询获取了所有文档并将其打印出来。

请注意,为了运行上面的示例,您需要安装MongoDB C++驱动程序和相关的依赖项。您可以在MongoDB的官方网站上找到更多关于C++驱动程序的信息和文档。

0