How to get OID of a BSON object as a hex string?

2.2k Views Asked by At

I am using the mongo-cxx driver trying to convert the object ID of a BSON object to a string

BSONObj r=some_function();
BSONElement oi;
r.getObjectID(oi);
OID o=oi.__oid();
cout<<"oid:"<<o.toString()<<endl;`

I am sure that the BSONObj has valid data but I get the following error:

BSONElement: bad type #somenumber

1

There are 1 best solutions below

0
On

The query object returns a pointer to the buffer where the BSONObj is stored. I went wrong when I did not use the function BSONObj::getOwned() to request a copy of the BSONObj which was causing the exception.