Search code examples
c++mongodbmongo-cxx-driver

Get OID (types::b_oid) as string in MongoDB C++ driver


I'm using MongoDB C++ driver (version 3.4.0 for reference). I need to get the _id of a given document. First, I grab the document:

bsoncxx::stdx::optional<bsoncxx::document::value> sub = conn["mydb"]["csubs"].find_one(...);

so I can access to the _id this way:

sub->view()["_id"].get_oid();

So far, so good.

As far as I have read in driver API this object is of type types::b_oid. However, I would need to get it as std::string.

Surprisingly, I haven't found any method in the types::b_oid class documentation for string conversion. I mean, the typical to_string() method so I can call something like:

sub->view()["_id"].get_oid().to_string();

Probably I'm missing something (because the use case seems to be too obvious :), but after a while checking documentation I haven't find the solution. Any help is welcome!


Solution

  • I think you can call to_string() from the value field:

    sub->view()["_id"].get_oid().value.to_string();
    

    Here's an example from the mongocxx github repo