Using the Mongo C Driver
I’m writing a Cocoa application to browse and administer a Mongo DB. This is a fun side-project. I’m using the Mongo driver from Objective-C, hence there might be differences for you.
First off, we need to connect to Mongo, and to do that, we need to tell Mongo about the connection information, namely the host and port:
1 mongo_connection_options opts;
2 strcpy(opts.host,
3 [[self.connectionInfo objectForKey:MEHost] cString]);
4 opts.port = [[self.connectionInfo objectForKey:MEPort] intValue];
5 /* mongo doesn't have a default port constant or define */
6 if (0 == opts.port) opts.port = 27017;
connectionInfo above is an instance of NSDictionary. The available keys are declared in NewConnectionController.
After we’ve prepared the connection options, it’s time to connect:
1 connection = (mongo_connection *)malloc(sizeof(mongo_connection));
2 if (!connection) return;
3
4 mongo_conn_return result = mongo_connect(connection, &opts);
5 if (mongo_conn_success == result) return;
connection above was declared as a pointer to a mongo_connection structure in DatabaseController. If the connection succeeds, I simply continue. If the connection fails, I fall-through and inform the user using an NSAlert, shown as a sheet.
I haven’t yet needed to authenticate to Mongo, but it seems simple to call mongo_cmd_authenticate().
Don’t forget the tests available in the mongo driver itself.