如何获取格式为“ bsoncxx :: v_noabi :: types :: bson_value :: view”的mongocxx gridfs id

问题描述

我正在使用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,111,87,114,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方法获得正确的格式。

解决方法

我找到了答案

    for(auto doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << "\n";

    bsoncxx::types::bson_value::view id =  doc["_id"].get_value();