Database Reference
In-Depth Information
Note that you explicitly generate the object
ID
using the
genOID()
function.
C++
BSON
objects are static, which means that the insert function can't modify them like it does
in other drivers. If you want a handle on the object id after insert, then you need to
generate it yourself.
Note also that you must convert the
BSONObjBuilder
into a
BSONObj
before it can
be used. You do this by calling the
BSONObjBuilder
's
obj()
method.
Now let's generate the same document using the helper macros.
BSON
and
GENOID
will save some typing:
BSONObj o = BSON( GENOID << "username" << "Jones" << "zip" << 10011 );
cout << o.jsonString();
Constructing the more complex document will be reminiscent of Java, where you have
to build each sub-object separately. Note that you build the array with the standard
BSONObjBuilder
, only you use numeric string indexes 0 and 1. This is in fact how
arrays are stored in
BSON
:
BSONObjBuilder site;
site.genOID().append("url", "org.mongodb");
BSONObjBuilder tags;
tags.append("0", "database");
tags.append("1", "open-source");
site.appendArray( "tags", tags.obj() );
BSONObjBuilder attrs;
time_t now = time(0);
attrs.appendTimeT( "lastVisited", now );
attrs.append( "pingtime", 20 );
site.append( "attrs", attrs.obj() );
BSONObj site_obj = site.obj();
Like before, you'll appreciate the macros for conciseness. Pay special attention to the
BSON_ARRAY
and
DATENOW
macros, and note what constructs they replace in the
BSONObjBuilder
version of the document:
BSONObj site_concise = BSON( GENOID << "url" << "org.mongodb"
<< "tags" << BSON_ARRAY( "database" << "open-source" )
<< "attrs" << BSON( "lastVisited" << DATENOW << "pingtime" << 20 ) );
Unique to C++ is the requirement that you explicitly mark
BSON
documents that will
be used as query selectors. One way to do this is with the
Query()
constructor:
BSONObj selector = BSON( "_id" << 1 );
Query * q1 = new Query( selector );
cout << q1->toString() << "n";
Again, the handy
QUERY
macro will usually be preferable:
Query q2 = QUERY( "pingtime" << LT << 20 );
cout << q2.toString() << "n";