【问题标题】:How to get mongocxx gridfs id in format "bsoncxx::v_noabi::types::bson_value::view"如何以“bsoncxx::v_noabi::types::bson_value::view”格式获取mongocxx gridfs id
【发布时间】:2020-08-19 13:10:52
【问题描述】:

我正在使用 mongocxx 3.6.0 驱动程序,我尝试从 gridfs 存储和接收字节。

我可以运行https://github.com/mongodb/mongo-cxx-driver/blob/releases/stable/examples/mongocxx/gridfs.cpp 中的示例代码,但我想搜索并获取合适的文件。

当我检查文档 http://mongocxx.org/api/current/classmongocxx_1_1gridfs_1_1bucket.html#aea1a02a75eb98a67788b94402ff90ba9 时,我使用的是 id 或文件名,但如何以正确的格式获取信息。

int main() {
// The mongocxx::instance constructor and destructor initialize and shut down the driver,
// respectively. Therefore, a mongocxx::instance must be created before using the driver and
// must remain alive for as long as the driver is in use.
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto db = conn["test"];
auto bucket = db.gridfs_bucket();

// "sample_gridfs_file" is the name of the GridFS file stored on the server. GridFS filenames
// are not unique.
auto uploader = bucket.open_upload_stream("sample_gridfs_file");

// ASCII for "HelloWorld"
std::uint8_t bytes[10] = {72, 101, 108, 108, 111, 87, 111, 114, 108, 100};

// Write 50 bytes to the file.
for (auto i = 0; i < 5; ++i) {
    uploader.write(bytes, 10);
}

auto result = uploader.close();



mongocxx::cursor cursor = bucket.find({});
for(auto doc : cursor) {
   std::cout << bsoncxx::to_json(doc) << "\n";

    bsoncxx::types::bson_value::view id = doc["_id"];

    std::cout << id.get_oid().value.to_string()<< std::endl;
    auto downloader = bucket.open_download_stream(id);

当在上面执行此操作时,它会抛出如下异常

error: conversion from ‘bsoncxx::v_noabi::document::element’ to non-scalar type ‘bsoncxx::v_noabi::types::bson_value::view’ requested

如何将元素转换为视图,或者通过 find 方法获取正确的格式。

【问题讨论】:

    标签: c++ mongodb-query gridfs mongo-cxx-driver


    【解决方案1】:

    我找到了答案

        for(auto doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << "\n";
    
        bsoncxx::types::bson_value::view id =  doc["_id"].get_value();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多