1

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!

fgalan
  • 11,732
  • 9
  • 46
  • 89
  • 1
    There are two ways depending whether you're trying to print as string or to convert value to string. Please see duplicate https://stackoverflow.com/a/35920720 – Wan B. Jan 27 '20 at 23:22

1 Answers1

2

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

SPM
  • 405
  • 1
  • 5
  • 16