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

How to get mongocxx gridfs id in format "bsoncxx::v_noabi::types::bson_value::view"

我正在使用 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 方法获取正确的格式。

我找到了答案

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

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