How to convert string to BSON using MongoDB C++ driver?

user837208 picture user837208 · Jan 9, 2012 · Viewed 7k times · Source

Similar to toString is there a way we can convert a string to BSON object? I need to remove a document using C++ driver the the remove function expects the query to have BSON object.

Answer

Tyler Brock picture Tyler Brock · Jan 14, 2012

Use the fromjson method found here:

http://api.mongodb.org/cplusplus/1.5.4/namespacemongo.html#a4f542be0d0f9bad2d8cb32c3436026c2

BSONObj mongo::fromjson (   const string &  str  )  
Create a BSONObj from a JSON <http://www.json.org> string.

In addition to the JSON extensions extensions described here http://mongodb.onconfluence.com/display/DOCS/Mongo+Extended+JSON, this function accepts certain unquoted field names and allows single quotes to optionally be used when specifying field names and string values instead of double quotes. JSON unicode escape sequences (of the form ) are converted to utf8.

Exceptions: MsgAssertionException if parsing fails. The message included with this assertion includes a rough indication of where parsing failed.