【问题标题】:Insert JSON into Mongocxx将 JSON 插入 Mongocxx
【发布时间】:2016-11-05 22:12:46
【问题描述】:

我目前正在尝试将 JSON 文件插入到我的 mongoDB 中。我已经看到过去通过使用 mongo::BSONObj 解决了这个问题......但这似乎不是一个选择,因为他们发布了用于 c++11 的新 mongocxx 驱动程序。这是我在 bsoncxx src 文件中找到的:

BSONCXX_API document::value BSONCXX_CALL from_json(stdx::string_view json);
/// Constructs a new document::value from the provided JSON text
///
/// @param 'json'
///  A string_view into a JSON document
///
/// @returns A document::value if conversion worked.
///
/// @throws bsoncxx::exception with error details if the conversion failed.
///

如何将我的 JSON 文件放入 stdx::string_view

谢谢!

【问题讨论】:

    标签: c++ json mongodb bson mongo-cxx-driver


    【解决方案1】:

    bsoncxx::stdx::string_view 可以从 std::string 构造。只需将文件内容(假设它包含单个 JSON 对象)加载到 std::string(可能通过 std::ifstream),然后将 std::string 传递给 bsoncxx::from_json。从bsoncxx::from_json 返回的对象是一个bsoncxx::document::value,它是一个包含BSON 文档的资源拥有类型。

    【讨论】:

    • 感谢您的回答,效果很好!有没有办法一次加载多个对象(例如数组和东西)?
    • 封闭实体必须是一个对象,但它当然可以包含嵌套数组和其他对象等。如果您希望将多个顺序存储在文本文件中的 JSON 文档加载到类似 @987654329 的文件中@ of bsoncxx::document::value,那么不,我们没有类似的东西,但你自己实现会很简单。
    • bsoncxx::document::value bsonObj = bsoncxx::from_json(your_json_string);
    猜你喜欢
    • 2019-01-21
    • 2019-11-20
    • 2018-11-28
    • 2014-02-26
    • 2016-10-10
    • 2021-08-22
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    相关资源
    最近更新 更多