Home > Mobile >  Strange behaviour insert_one mongocxx 3.6
Strange behaviour insert_one mongocxx 3.6

Time:02-10

Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code:

  const mongocxx::database& db = _pClient->database(_dbName.c_str());
  mongocxx::collection& collection = db.collection(collectionName.c_str());
  auto retval = collection.insert_one(view);
  bsoncxx::oid oid = retval->inserted_id().get_oid().value;
  std::string str = oid.to_string()

Unfortunately it looks like when I try to convert the object id to a string the string is unreadable (corrupted like). I am using mongocxx version 3.4 and mongodb 4.0.28 (the two versions should be compatible according to the mongodb website). Do you know what could be the problem here?

Here what I can see through the debugger: visual studio debugger

Here what I can see thorugh the mongodb client: mongodb client

CodePudding user response:

The debugger is showing you the individual bytes in decimal.

I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal

mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0"  ((n & 255).toString(16))).slice(-2)).join("")
6203e829a8590000a30058b2
  • Related