Database Reference
In-Depth Information
D.3.2
Connections
You can easily create single-node connections by instantiating a DBClientConnection .
Always wrap this in a try block:
DBClientConnection conn;
try {
conn.connect("localhost:27017");
}
catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
Connecting to a replica set first requires that you build a vector containing HostAnd-
Port objects. You then pass the name of the replica set and the vector to the
DBClientReplicaSet constructor. You can check the contents of the object by calling
toString() :
std::vector<HostAndPort> seeds (2);
seeds.push_back( HostAndPort( "localhost", 30000 ) );
seeds.push_back( HostAndPort( "localhost", 30001 ) );
DBClientReplicaSet repl_conn( "myset", seeds );
try {
repl_conn.connect();
catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
cout << repl_conn.toString();
D.3.3
Sample program
The main thing to notice in the C++ code sample is that there are no explicit classes
for abstracting databases and collections. All inserts, updates, queries, and deletes go
through the connection object itself. You specify the database and collection as the
first argument to these methods in the form of a namespace ( crawler.sites ):
#include <iostream>
#include <ctime>
#include "client/dbclient.h"
using namespace mongo;
int main() {
DBClientConnection conn;
try {
conn.connect("localhost:27017");
}
catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
BSONObj doc = BSON( GENOID << "url" << "org.mongodb"
<< "tags" << BSON_ARRAY( "database" << "open-source" )
Search WWH ::




Custom Search