Jason Welch
Jason Welch

Reputation: 336

reading/writing to different replicasets in Mongo

So I like the idea of having separate db's for handling writes (there could be say 2 write db's and then each could have 3 replicas for reads).

    $mongo = new   Mongo("mongodb://localhost:27017",array('connect'=>true,'timeout'=>2000, 'persist'=>'test_mongodb_con','replicaSet'=>true));

and to test...

    $user = array('email'=>'[email protected]','firstname'=>'test','lastname'=>'user','twitter'=>'@test','time'=>date('m:i:s'));

    $mongo->test->testuser->insert($user);

    $cursor = $mongo->test->testuser->find()->slaveOkay(true);

but the ONLY difference when slaveOkay is true is that the flag key has a value of 4 - but it's not telling me which db it's actually using. Does it matter that I have them on separate ports since mongod is aware of all replicas?

I've already searched this topic for hours and can't find anything that completely answers my question. I've read the php docs, the mongo docs, etc...still confused.

Upvotes: 1

Views: 1276

Answers (1)

William Z
William Z

Reputation: 11129

There is a difference between replication and sharding in MongoDB.

If you're using replication, there is only one node that is receiving writes -- the primary node. Your driver connects to the replica set, and all writes go to the single primary node, whichever node it happens to be at the time.

If you want to distribute writes among multiple nodes using MongoDB, then you have to set up sharding. With sharding, your driver will connect to a router process ('mongos') which will automatically route the write to the correct node in the cluster.

Replication is used for durability, fail-over, backup, and (occasionally) read scaling.

By default, all reads go to the primary node as well. The 'slaveOK' flag (which has been deprecated in favor of Read Preference) allows reads to go to the secondary nodes. This allows query load to be distributed off of the primary node, at the cost of potentially reading stale data.

Without the SlaveOK flag, you're guaranteed to read back the data that you just wrote (unless someone else has modified it since then). With the SlaveOK flag, there is no such guarantee: the secondary could be seconds, minutes, or even hours behind the primary.

If you want to do write scaling with MongoDB, then you need to set up sharding.

Upvotes: 6

Related Questions