温馨提示×

c++ bson文档如何创建

c++
小樊
81
2024-09-15 15:33:15
栏目: 编程语言

在C++中,要创建一个BSON文档,你需要使用一个BSON库,例如mongo-cxx-driver

首先,确保你已经安装了mongo-cxx-driver。你可以按照官方文档中的说明进行安装:mongo-cxx-driver installation

以下是一个简单的示例,展示了如何使用mongo-cxx-driver创建一个BSON文档:

#include<iostream>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/exception/exception.hpp>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;

int main() {
    try {
        // 创建一个BSON文档
        auto doc = document{} << "name" << "John Doe"
                              << "age" << 30
                              << "city" << "New York"
                             << finalize;

        // 将BSON文档转换为JSON字符串
        std::string json_str = bsoncxx::to_json(doc.view());

        // 输出JSON字符串
        std::cout << "BSON document as JSON: "<< json_str<< std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what()<< std::endl;
        return 1;
    }

    return 0;
}

这个示例中,我们使用了bsoncxx::builder::stream::document来创建一个BSON文档。我们向文档中添加了三个字段:nameagecity。然后,我们使用bsoncxx::to_json()函数将BSON文档转换为JSON字符串,并将其输出到控制台。

注意:在编译此代码时,确保链接mongo-cxx-driver库。例如,使用g++编译器时,你可以使用以下命令:

g++ your_file.cpp -o your_output_file $(pkg-config --cflags --libs libmongocxx)

0