build BSON string recursively and re-use for query

63 views
Skip to first unread message

Mick

unread,
Sep 19, 2012, 5:31:33 PM9/19/12
to mongod...@googlegroups.com
In C++ , instead of doing this:
qryStr = QUERY("d" << 1 << "t" << 2 << "l" << "mine");
bsonStr = BSON("d" << 1 << "t" << 2 << "l" << "mine");
 
can I do something like
strStream << "d" << 1 << "t" << 2 << "l" << "mine";
qryStr = QUERY(strStream);
bsonStr = BSON(strStream);
 
I tried defining strStream as stringstream, but it's complaining. 
Is that even possible in C++?
 
Thank you in advance.

David Hows

unread,
Sep 20, 2012, 12:16:55 AM9/20/12
to mongod...@googlegroups.com
Hi Mick,

The BSON function is actually a macro with a definition of
 #define BSON(x) (( mongo::BSONObjBuilder(64) << x ).obj())

You can build an object by creating a BSONObjBuilder and then just start appending things too it, like so;

BSONObjBuilder query2;
query2.append("d", 1);
query2.append("t", 2);
query2.append("l", "mine");

Finally, when you need to use it for a query just use the .obj() method.

eg conn.query(ns, query2.obj());

Hope that helps,

David

Mick

unread,
Sep 20, 2012, 2:42:16 PM9/20/12
to mongod...@googlegroups.com
Thank you, David :)
I was under the impression that I had to use QUERY(x) to query mongo, but good to know that I can use BSON(x) instead.
for example: instead of conn.query(dbName, QUERY(x));
I can use conn.query(dbName, BSON(x));

David Hows

unread,
Sep 20, 2012, 7:11:43 PM9/20/12
to mongod...@googlegroups.com
Absolutely correct.

Both the QUERY macro and the BSON macro provide a BSONObj data type.

Cheers,

David
Reply all
Reply to author
Forward
0 new messages