C++ bucket.delete_file() does not seem to accept any type of oid

I am developing a project using GridFS to save large files as binary blob into MongoDB; I am using C++ API;

So far I am able to save large files into bucket, which in mongosh gives me two collections fs.chunks and fs.files;

However, I have problems to delete files from the bucket. I tried to use the C++ API and below are the code snip I am using:

# code that successfully assign "doc" as bsoncxx::v_noabi::document::view&


or even

None of the above code allow me to compile my code, error message always says

error: no matching function for call to ‘mongocxx::v_noabi::gridfs::bucket::delete_file(bsoncxx::v_noabi::document::view&)’ 
or similar input type not match delete_file() input variable.

I looked the official document says that the delete_file() accept and input variable “id” can be the type of
which means anything in BSON;

But even I tried to convert the oid to a bson_value object does not fix the problem. I suspect there could be some bugs in the function? And I would like to seek help or advice from community. Thanks again.

Hi @katlv_zheng

Welcome to MongoDB forums!

You need to convert the _id field of your document to a bsoncxx::types::bson_value::view using the bsoncxx::types::bson_value::view_or_value constructor. I have shared sample code below.

// ---------------UPLOAD---------------//
     // "sample_gridfs_file" is the name of the GridFS file stored on the server.
    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();

    // // ---------------DELETE---------------//

    // Delete the uploaded file by using the id. 
    // "id" can be reused directly, but construct a document for the sake of example.
    bsoncxx::types::bson_value::view id = result.id();
    bsoncxx::document::value doc_value = bsoncxx::builder::basic::make_document(bsoncxx::builder::basic::kvp("_id", id));
    bsoncxx::document::view doc_view = doc_value.view();
    bsoncxx::types::bson_value::view_or_value id_value {doc_view["_id"].get_value()};
    // Pass the id to the delete_file

Hi Rishabh, thanks the sample code and it solves my problem. Didn’t expect the syntax need to be like this though. Thanks again!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.