We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

MongoDB Split Read and Write

How to split mongodb write connection and read connection ? I have 3 mongodb server which is configured as replica. this is my database connection setting :

$mongo = new MongoClient(
    "mongodb://100.0.0.1:4000,100.0.0.2:4000,100.0.0.3:4000/mydatabase?replicaSet=loadbalance",[
        "username" => "user",
        "password" => "****"
    ]
);
return $mongo->selectDB("mydatabase");

I need split like this

MongoA (master) => read,write MongoB => read MongoC => read

edited Feb '17

Your constructor example shows only that you have a list of MongoDB instances and the driver will decide which instance to use per Round robin or other strategy.

Your app is in a perfect position to decide upon whenever to use Read instance, or Write instance. That said, depends on the way how your app is designed. For reports etc. you want to target Read instance obviously. For writes, the opposite (Write instance).

So In general, you'd need different database connections / service definitions for each instance (Read, Write...). That way you can use parts of app which strictly rely on reads to use something like: $this->mongoReadService->(["yourQueryHere..."]).

P.S. PECL mongo extension is deprecated.

thanks for your solution. I'am looking solution like Mysql. https://php-phalcon-docs.readthedocs.io/en/latest/api/Phalcon_Mvc_Model_Manager.html

I can set read connection using setReadConnectionService and set write connection using setWriteConnectionService