News Archive
PhpRiot Newsletter
Your Email Address:

More information

Lithium: Connect to MongoDB replica set

Note: This article was originally published at Planet PHP on 16 April 4080.
Planet PHP

I was initially a little unclear about how to connect my Lithium application to my MongoDB replica set while specifying multiple serves, I've settled with: Connections::add('default', array('type' = 'MongoDb', 'host' = 'localhost:12345,washington.mongo:12345', 'replicaSet' = true, 'database' = 'wiu'));

I'm listing multiple servers that form my replica set in the host field as a comma separated list. While you technically only need to list one (and the driver should discover the rest), it's a good idea in case the one you have listed goes down.

Well, secretly, that's not actually how I'm connecting to MongoDB. I'm also telling Lithium that it should set a read preference of RP_NEAREST. This option isn't available yet in lithium, but I've got an open pull request to fix that. I'm actually connecting to MongoDB like this: Connections::add('default', array('type' = 'MongoDb', 'host' = 'localhost:12345,washington.mongo:12345', 'replicaSet' = true, 'database' = 'wiu', 'readPreference' = Mongo::RP_NEAREST));

Note: Specifying your read preference (and still having everything work) currently requires an un-released version of the MongoDB driver. You either need this fix, so you can build from source. Or presumably the fix will be included in 1.3.0 BETA 3.