Search code examples
c++mongodb-querygridfsmongo-cxx-driver

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


I am working with mongocxx 3.6.0 driver, I try to store and receive bytes from gridfs.

I am able to run the example code in https://github.com/mongodb/mongo-cxx-driver/blob/releases/stable/examples/mongocxx/gridfs.cpp, but I want to search and get suitable file.

When I examine the documentation http://mongocxx.org/api/current/classmongocxx_1_1gridfs_1_1bucket.html#aea1a02a75eb98a67788b94402ff90ba9, I am doing this with the id or filename but how to get informations in proper format.

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);

When done this in above, it throws exception like below

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

How to convert element to view, or get in proper format by find method.


Solution

  • I found the answer

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